在 Laravel 中以相同的方法将变量从一个查询传递到另一个查询

时间:2021-01-26 15:09:13

标签: php sql laravel

我试图将一个变量从一个查询传递到另一个查询(下面是代码) 如果我使用 $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

提前致谢

1 个答案:

答案 0 :(得分:0)

这是你可以做的

$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);