問題描述
我有一個簡單的相冊和圖片設置,每個相冊都有很多圖片.我可以正常獲取所有數據,但我想將返回的圖像數量限制為 3.我嘗試過像這樣傳遞閉包:
I have a simple set-up of Albums and Images, each album has many images. I can get all the data fine but I want to limit the returned number of images to 3. I have tried passing a closure like so:
Album::with(['images' => function($query) { $query->take(3);}])->get();
這確實將圖像數量限制為 3,但將圖像總數限制為 3,但我想將每個相冊限制為 3 個圖像.所以第一個相冊會按預期顯示 3 張圖片,但所有其他相冊都沒有圖片.
This does limit the number of images to 3 but it limits the total count of images to 3 but I want to limit each album to 3 images. So the first album will show 3 images as expected but all the other albums have no images.
我嘗試向我的模型中添加一個新方法,如下所示:
I have tried adding a new method to my model like so:
public function limitImages()
{
return $this->hasMany('AppImage')->limit(3);
}
我在控制器中調用它:
Album::with('limitImages')->get();
但這根本不限制返回的圖像數量
But this doesn't limit the image count returned at all
推薦答案
我覺得你會很快遇到 N+1 問題,試圖實現這一點.只需在它返回的集合中執行此操作:
I feel you'd quickly run into an N+1 issue trying to accomplish this. Just do it in the collection that it returns:
Album::with('images')->get()->map(function($album) {
$album->setRelation('images', $album->images->take(3));
return $album;
});
這篇關于Laravel Eloquent 關系的限制結果的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!