Php 如何在Laravel中将嵌套关系数组转换为单个数组
项目模型:Php 如何在Laravel中将嵌套关系数组转换为单个数组,php,mysql,laravel,Php,Mysql,Laravel,项目模型: public function item_makes(){ return $this->hasMany(ItemMake::class,'item_id','id'); } 在ItemMake模型中: public function make(){ return $this->belongsTo(Make::class,'make_id','id'); } 我需要根据项目id获取所有make的数组。如何实现这一点?提前谢谢。试试这样的方法: Item
public function item_makes(){
return $this->hasMany(ItemMake::class,'item_id','id');
}
在ItemMake模型中:
public function make(){
return $this->belongsTo(Make::class,'make_id','id');
}
我需要根据项目id获取所有make的数组。如何实现这一点?提前谢谢。试试这样的方法:
Item::findOrFail(1)
->with('item_makes.make')
->get()
->pluck('make')
->flatten()
->toArray()
试试下面的
wherehas
方法
$makes = Make::whereHas('item_makes', function ($query) use($item_id) {
$query->where('item_id', $item_id);
})->get();
这对我有用
$item = Item::findOrFail(1)
->item_makes()
->with('make')
->get()
->pluck('make')
->flatten()
->toArray();
非常感谢先生:)您也可以使用Make model中的
whereHas
方法。这样,您就不需要压扁或拔毛了。我同意,但是您还需要一个子查询来只获取属于项的make,以及具有给定id的项的make。