我想获取不同的表数据并将它们保存在数组中。
$int_payment = IntPayments::where('month',$month_year)->groupBy('interviewer_id')->get();
foreach ($int_payment as $inter) {
$inters[] = User::where('id',$inter->interviewer_id)->get();
$inters['payment_status'] = $inter->payment_status;
}
return response()->json(['inters'=>$inters,'month'=>$month]);
这里我从来自int_payment表的interviewer_id获取用户表中的用户名。现在$inters[]
包含特定用户的所有数据。现在我想从int_payments表中只获取一列并将其添加到数组$ inters。上面的代码不能按预期工作。结果这个。上面的代码还将支付状态添加到第一个数组值,而不是其他数组值。像这样
{"inters":{"0":[{"id":1,"name":"Naveen1","phone":"7841237900",}],"payment_status":"unpaid","1":[{"id":2,"name":"john","phone":"7845123900",}]}}
{"inters":{"0":[{"id":1,"name":"Naveen1"}],"payment_status":"unpaid",}
但是我希望它像这样包含在数组中
{"inters":{"0":[{"id":1,"name":"Naveen1","payment_status":"unpaid"}],}
{"inters":{"1":[{"id":2,"name":"john","payment_status":"paid"}],}
答案 0 :(得分:0)
如果我告诉你你想要这样的东西:
{"inters":{"0":[{"id":1,"name":"Naveen1","payment_status":"unpaid"}],}
或许在您拥有的集合中使用push
会对您有所帮助:
$int_payment = IntPayments::where('month',$month_year)->groupBy('interviewer_id')->get();
foreach ($int_payment as $key => $inter) {
$inters = User::where('id',$inter->interviewer_id)->get(['id', 'name']);
$inters_payment[] = $inters->push(['payment_status' => $inter->payment_status]);
}
return response()->json(['inters'=>$inters_payment,'month'=>$month]);
顺便说一句,我不知道这个$month
变量的功能在哪里,但我只是将它留在示例代码中。
然而,有一个警告是,为什么不采用laravel的关系来满足User
和IntPayments
模型之间的互动?因为我可以观察到,如果你有数千个IntPayments
返回,那么只是为了这个函数,你将在users
表上执行数千个查询。
你可以有一些简单而优雅的东西:
$inters = IntPayments::where('month',$month_year)->groupBy('interviewer_id')->with('user')->get();
$result = [];
foreach($inters as $key => $inter)
{
$result[$key]['id'] = $inter->user->id;
$result[$key]['name'] = $inter->user->name;
$result[$key]['payment_status'] = $inter->payment_status;
}
然后您可以将您的回复视为:
return response()->json(['inters'=> $result]);