[英]Laravel Model: how to get all relations as array with custom array keys?
[英]How to get array of nested relations into single Array in 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');
}
我需要獲取所有基於item_id的品牌數組。 如何實現呢? 提前致謝。
嘗試這樣的事情:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.