我从类别到内容有很多关系,我希望每个类别限制 4 个内容。
我想限制与语言有子关系的关系内容的结果
我的代码
Category::with(['contents.languages' => function($query){
$query->limit(4);
}])
->get();
但我在日志中看到限制适用于语言关系,而不是内容,我想要的是限制内容
最佳答案
如果您使用 get() 检索多个父模型,take() 和 limit() 函数将无法使用预加载。
所以你必须换一种方式,
$categories = Category::with('contents')->get();
获取$categories
后,你可以像下面这样做foreach循环,
$contents = [];
foreach($categories as $category){
$category->limitedContents = $category->contents()->with('languages')->limit(4);
}
通过这样做,您将获得所有类别中每个类别的 4 个内容,并带有 limitedContents
。
Note: Here I used name as 'limitedContents' because you have already defined contents relationship.
关于mysql - 具有子关系的关系中的 Laravel Eloquent 限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49731582/