簡體   English   中英

Laravel Eager以一對多關系加載指定列的集合

[英]Laravel Eager loading collection of specified column in one to many relationship

是否可以在一個查詢中執行這些操作?

$detail = Goods::find(1);
$detail->pictures = $detail->pictures()->lists('link');
// output
[
  'id' => 1,
  'name' => 'IPhone',
  'pictures' => [
    0 => 'http://whatever.com/1.jpg',
    1 => 'http://whatever.com/2.jpg',
   ],
]

我試過了

Goods::with(['pictures' => function($query){
    $query->select('link');
}])->find($id);

沒有預期的輸出

您還需要選擇外鍵。 您可以使用toArray()將集合轉換為數組:

Goods::with(['pictures' => function($query){
    $query->select('link', 'good_id');
}])->find($id)->toArray();

有了您上面的查詢,你怎么會知道哪個Good屬於哪個Picture無鑰匙? 雄辯的人也不知道,所以它不能匹配相關的模型。

這是您需要的:

$good = Goods::with(['pictures' => function($query){
           $query->select('id', 'good_id', 'link');
        }])
        ->find($id);

然后,您可以使用集合的pluck方法:

$good->pictures = $good->pictures->pluck('link');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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