[英]Passing a variable from one query to another in same method in Laravel
I am trying to pass a variable from one query to another (bellow is the code) If I use $data[0]->name this will give a fixed values which I need something variable like in $data[$i]->name or something.我正在尝试将变量从一个查询传递到另一个查询(下面是代码)如果我使用 $data[0]->name 这将给出一个固定值,我需要像 $data[$i]-> 这样的变量名字什么的。
Controller: Controller:
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);
}
View:看法:
@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
Thank you in advance先感谢您
Here is what you can do这是你可以做的
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.