Laravel口才的极限关系结果 [英] Laravel Eloquent limit results for relationship

查看:50
本文介绍了Laravel口才的极限关系结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的相册和图像设置,每个相册都有很多图像.我可以很好地获取所有数据,但我想将返回的图像数限制为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('App\Image')->limit(3);
}

然后在我的控制器中将其称为:

And I call this in my controller:

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口才的极限关系结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆