我有多个类别,每个类别都有很多帖子,我想为每个类别提取4个帖子,我使用此代码:
$catsWitposts= $this->categories->with(['posts' => function($query){
$query->where('show', '=', 1);
$query->limit(4);
$query->orderBy('created_at','desc');
}])->get();
但此代码显示所有类别的4个帖子
查询结果应显示:
cat-01
post-01
post-02
post-03
post-04
cat-02
post-05
post-06
post-07
post-08
cat-03
post-09
post-10
post-11
post-12
....
感谢
答案 0 :(得分:0)
一个例子
//Grab all categories
$categories = Category::all();
//This array will contain our result
$latest_posts_by_category = [];
//We use this array to save each post id that we have already collected
//in order to avoid to put it twice.
//Remember that some posts may belongs to many categories.
$ids = [];
//For each category we grab the latest post with the latest first associated category
//(Note that you can collect all associated categories if you want by remove the first() in the closure)
foreach($categories as $category){
$post = Post::with(['categories' => function($query){
$query->latest()->first();
}])
->online() //You may have a custom method like this.
->latest()
->whereHas('categories', function($query) use($category) {
$query->whereName($category->name);
})->take(1)->first();
//We take in account the fact that
//some posts may belongs to many categories.
//Obviously, we don't want to put it twice
if(!in_array($post->id, $ids)){
$latest_posts_by_category[] = $post;
$ids[] = $post->id;
}
}
//You can now use $latest_posts_by_category as you want