从Laravel的相关表中获取有限数量的结果

时间:2013-11-26 18:34:22

标签: php mysql laravel laravel-4

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中执行此操作?

1 个答案:

答案 0 :(得分:1)

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

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";
    }
}