【问题标题】:Get limited amount of results from related table in Laravel从 Laravel 的相关表中获取有限数量的结果
【发布时间】:2013-11-26 18:34:22
【问题描述】:

表格

post            category
-----           ----------
id              id
name            name
category_id

每个类别的帖子数量有限(如果类别有帖子)

$categories = Category::get();
$categores_with_posts = array();

foreach($categories as $category)
{   
    $category_data = array(
        'posts' => Post::where('category_id', $category['id'])->take(10)->get()->toArray(),
        'category_id' => $category['id'],
        'name' => $category['name']
    );

    if(!empty($category_data['posts'])) {
        $categores_with_posts[] = $category_data;
    }
}

如何在 Laravel 中使用一个查询来做到这一点?

【问题讨论】:

    标签: php mysql laravel laravel-4


    【解决方案1】:

    这是已测试代码,但您应该能够在这两个模型之间创建关系:

    class Post extends Eloquent {
    
        public function category()
        {
            return $this->belongsTo('Category');
        }
    
    }
    
    class Category extends Eloquent {
    
        public function posts()
        {
            return $this->hasMany('Post');
        }
    
        public function postsTop10()
        {
            return $this->posts()->take(10);
        }
    
    }
    

    然后用它来得到你的结果:

    $categories = Category::with('postsTop10')->get();
    
    foreach($categories as $category)
    {   
        foreach($category->postsTop10 as $post)
        {
            echo "$post->name";
        }
    }
    

    【讨论】:

    • 这在 SQL 中运行为:select * from post where post.category_id in (?, ?, ?, ?) limit 10 所以我只能从 1 个类别中获得 10 个帖子。
    • 这里刚刚测试过,当然需要使用$category->postsTop10。已编辑。
    • 我在$categories = Category::with('postsTop10')->get(); 之后使用了dd(DB::getQueryLog()),我得到了sql select * from post where post.category_id in (?, ?, ?, ?) limit 10。在 foreach 周期中,我没有获得额外的数据,因此 1 个类别的 10 个帖子仍然相同。要使其工作,只需通过$categories = Category::get(); 获取所有类别然后foreach($category->postsTop10 as $post) 将为每个类别获得10 个帖子。这不是在单个查询中完成的,但我想它仍然是正确的方法。这很有帮助:) 谢谢
    猜你喜欢
    • 2019-09-09
    • 2012-03-22
    • 1970-01-01
    • 2020-03-22
    • 2014-03-02
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多