Laravel 4模型,具有多个表的属性

时间:2013-09-11 04:15:59

标签: sql join orm laravel laravel-4

我想要一个属于另一个的模型。在我的控制器中,我想获得该模型中的所有项目,但我也希望它所属的表中的属性。例如:

class Comment extends Eloquent {

    public function post()
    {
        return $this->belongsTo('Post');
    }

}

在我的控制器中,我可以执行以下操作来获取评论数据:

$comments = Comment::first();

但是,这只会给我评论表中的数据(并且没有来自posts表的联接数据)。我希望每个评论所属的行的posts表中的数据可用作我的Comment模型的属性。我知道我也可以执行以下操作来从posts表中获取数据:

$ comments = Comment :: first();

这样做的问题是它使用两个数据库查询(#1来获取注释,#2来获取它所属的发布数据)。有没有办法让我从两个表中获取数据到我的模型中,相当于一个连接语句:

SELECT * FROM comments LEFT JOIN posts ON comments.post_id = posts.id

我知道我手动构建连接查询而不使用我的Comment或Post模型,但我在Comment模型中有几个方法,我希望能够使用检索到的数据。有谁知道我怎么能做到这一点?

3 个答案:

答案 0 :(得分:4)

来自documentation on eager loading

  

值得庆幸的是,我们可以使用预先加载来大幅减少查询次数。可以通过with方法[...]

指定应该加载的关系

使用with()参数将使用一对多关系中的常数†查询。因此,这是查询应该在一个查询中检索您的相关帖子的评论:

$comments = Comments::with('post')->get();

†持续数量的查询,而不是每个评论数量的查询计数线性增加

答案 1 :(得分:1)

如果您只想在后台完成一个查询而不使用with()来获得结果,则可以使用fluentjoin()

SELECT * FROM comments LEFT JOIN posts ON comments.post_id = posts.id

等于:

DB::table('comments')
    ->join('posts','comments.post_id','=','posts.id','left')
    ->get();

但我认为添加groupBy()语句会给你带来更好的结果:

示例:

DB::table('comments')
    ->join('posts','comments.post_id','=','posts.id','left')
    ->groupBy('comments.id')
    ->get();

但我更喜欢在我的项目中使用其他答案:

Comment::with('post')->get();

答案 2 :(得分:0)

$ comments :: all() - > with('post') - > get()