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