简体   繁体   English

eloquent 获得所有类别的 4 个帖子

[英]eloquent get 4 posts from all categories

i have some categories and many posts in each category i want to get all categories with its last 4 posts我有一些类别和每个类别中的许多帖子我想获得所有类别的最后 4 个帖子

my code with eloquent is:我的 eloquent 代码是:

$allcats = Category::whereHas('posts')->with(['posts' => function($q){
            $q->take(4);
}])->get();

but the problem is: this query will take just and just 4 post (4 post from all of the categories)但问题是:此查询仅需要 4 个帖子(所有类别中的 4 个帖子)

can do this with eloquent?可以用 eloquent 做到这一点吗? or can id do this with query builder??或者可以用查询生成器来做这个吗?

From the Laravel docs on Constraining Eager Loads来自 Laravel 文档约束急切负载

[!] The limit and take query builder methods may not be used when constraining eager loads. [!] 限制急切加载时可能不使用limittake查询构建器方法。

So you would have to create another relationship method on your class Category like this因此,您必须像这样在 class Category上创建另一种关系方法

public function lastPosts()
{
  return $this->hasMany('App\Post')->take(4);
}

then use it instead然后改用它

$allcats = Category::whereHas('posts')->with('lastPosts')->get();

Or use a raw query或使用原始查询

$allcats = Category::whereHas('posts')->with(['posts' => function($q){
            $q->orderBy('created_at')->selectRaw('max(4)');
}])->get();

Hope this helps希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM