我只需要获取以下查询返回的roomnumber
数组:
$roomnumbers = Room::with(['floorroomcount' => function($query){
$query->with('roomnumber')->get();
}])->where('roomtype_id', $roomtype_id)->get();
尝试:
以下采摘返回floorroomcount
$roomnumbers->pluck('floorroomcount');
但是我需要roomnumber
数组,我怎么能得到?
答案 0 :(得分:5)
这会在一个集合中为您提供所有roomnumber
个结果:
$roomnumbers->pluck('floorroomcount')->collapse()->pluck('roomnumber')->collapse();
答案 1 :(得分:1)
这是有效的,但有很多循环和直接回声,如果有什么可以简化,请告诉我:
$roomnumbers = Room::with(['floorroomcount.roomnumber'])->where('roomtype_id', $roomtype_id)->get();
$floorroomcounts = $roomnumbers->pluck('floorroomcount');
$records = $floorroomcounts->map(function($floorroomcount, $value){
return $floorroomcount->pluck('roomnumber')->flatten();
})->values()->all();
foreach($records as $record){
foreach($record as $row){
echo '<option value='.$row->id.'>'.$row->roomnumber.'</option>';
}
}
//return response()->json($roomnumbers);
答案 2 :(得分:1)
您可以这样缩短@Jonas Staudenmeir的答案:
$roomnumbers->pluck('floorroomcount.*.roomnumber.*')->collapse();
pluck('*')
在此特定情况下与collapse()
基本相同。
答案 3 :(得分:0)
尝试,
$roomnumbers = Room::with(['floorroomcount' => function($query){
$query->with('roomnumber')->get();
}])
->where('roomtype_id', $roomtype_id)
->get();
$records = $roomnumbers->map(function($element, $value){
return $element->map(function($e, $v){
return $e->roomnumber;
});
})->values()->all();
map()
是一个Laravel集合方法,因此您需要在控制器顶部导入集合外观,如:use Illuminate\Support\Collection;