首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel雄辩的关系(包含上一篇文章的类别)

Laravel雄辩的关系(包含上一篇文章的类别)
EN

Stack Overflow用户
提问于 2014-06-04 03:14:31
回答 1查看 681关注 0票数 0

我有多个类别,每个类别都有许多帖子,我想为每个类别获取4个最后的帖子,我使用以下代码:

代码语言:javascript
复制
$catsWitposts= $this->categories->with(['posts' => function($query){
                        $query->where('show', '=', 1);
                        $query->limit(4);
                        $query->orderBy('created_at','desc');
                    }])->get();

但是这段代码显示了所有类别的4个帖子

查询结果应显示:

代码语言:javascript
复制
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
....

谢谢

EN

回答 1

Stack Overflow用户

发布于 2014-09-08 17:52:10

一个例子

代码语言:javascript
复制
//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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24023166

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档