[英]How to get array of nested relations into single Array in Laravel
Item Model: 物品型号:
public function item_makes(){
return $this->hasMany(ItemMake::class,'item_id','id');
}
In ItemMake Model : 在ItemMake模型中:
public function make(){
return $this->belongsTo(Make::class,'make_id','id');
}
I need to get array of all make based on item_id. 我需要获取所有基于item_id的品牌数组。 How to achieve this? 如何实现呢? Thanks in Advance. 提前致谢。
Try something like this: 尝试这样的事情:
Item::findOrFail(1)
->with('item_makes.make')
->get()
->pluck('make')
->flatten()
->toArray()
Try wherehas
method something like this 尝试在wherehas
像这样的方法
$makes = Make::whereHas('item_makes', function ($query) use($item_id) {
$query->where('item_id', $item_id);
})->get();
This worked for me. 这对我有用。
$item = Item::findOrFail(1)
->item_makes()
->with('make')
->get()
->pluck('make')
->flatten()
->toArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.