簡體   English   中英

如何在Laravel中將嵌套關系數組轉換為單個數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM