【问题标题】:Passing a variable from one query to another in same method in Laravel在 Laravel 中以相同的方法将变量从一个查询传递到另一个查询
【发布时间】:2021-01-26 15:09:13
【问题描述】:

我正在尝试将变量从一个查询传递到另一个查询(下面是代码) 如果我使用 $data[0]->name 这将给出一个固定值,我需要一些变量,例如 $data[$i]->name 或其他东西。

控制器:

  public function accounts($country) {

    
    $data= DB::table("invoices")
        ->where("country", $country)
        ->select([ "name",
                    DB::raw("sum(case when type='income' then amount else 0 end) as income"),
                    DB::raw("sum(case when type='outcome' then amount else 0 end) as outcome")
                ])
        ->groupBy("name")
        ->orderBy("name", "DESC")
        ->get();


    $payments= DB::table("payments")
        ->where("name", $data[0]->name) // here is the variable I want to pass from the above $data query
        ->where("country", $country)
        ->select([  
                    DB::raw("sum(case when type='income' then amount else 0 end) as payment_income"),
                    DB::raw("sum(case when type='outcome' then amount else 0 end) as payment_outcome")
                ])
        ->groupBy("name")
        ->orderBy("name", "DESC")
        ->get();

    return view('accounting.accounts')
    ->with('accounts',$data)
    ->with('payments',$payments);

   }

查看:

 @foreach($accounts as $account)
   @foreach($payments as $payment)
     <tr>
        <th>{{$account->name}}</th>
        <td>{{$account->income}}</td>
        <td>{{$payment->payment_income}}</td>
        <td></td>
        <td>{{$account->outcome}}</td>
        <td>{{$payment->payment_outcome}}</td>
        <td></td>
     <tr>
  @endforeach
@endforeach

提前谢谢你

【问题讨论】:

  • 是否要获取第二个查询中所有 $data 行的数据?
  • 所以你想要一个whereIn,因为你要找多个?
  • 我想获取第二个查询中与 $data->name 的第一个查询的运行时间匹配的所有行的数据。好像它是一个 $data[$i]->name
  • @AmjadI.Bawarshi 为此,我认为您应该使用 foreach 来遍历 $names 的所有值。对于每个结果,将它们添加到表格中,然后在您的视图中显示。

标签: php sql laravel


【解决方案1】:

你可以这样做

$names = $data->pluck('name');

$payments= DB::table("payments")
        ->where("country", $country)
        ->whereIn("name", $names) 
        ->select([  
                    DB::raw("sum(case when type='income' then amount else 0 end) as payment_income"),
                    DB::raw("sum(case when type='outcome' then amount else 0 end) as payment_outcome")
                ])
        ->groupBy("name")
        ->orderBy("name", "DESC")
        ->get();
return view('accounting.accounts')
->with('accounts',$data)
->with('payments',$payments);

【讨论】:

  • 有什么问题?
  • 我已经编辑了where子句首先出现的答案。此外,如果 pluck 不起作用,请尝试使用 foreach 获取 $names 数组中的所有名称,其余的应该相同
  • 它检索到空值。我的表在视图中是空的
  • 更新后,您的代码似乎可以工作,但我得到重复值...请看这个截图pasteboard.co/JLrRJ50.png我需要它按名称分组,所以每行只有一个客户名称跨度>
  • 您是否在 $names 中得到重复值?
猜你喜欢
  • 2020-11-30
  • 2016-04-22
  • 1970-01-01
  • 2020-01-09
  • 1970-01-01
  • 2020-11-13
  • 1970-01-01
  • 2014-08-31
  • 1970-01-01
相关资源
最近更新 更多