Laravel 4.1渴望加载与约束的嵌套关系 [英] Laravel 4.1 Eager Loading Nested Relationships with Constraints

查看:246
本文介绍了Laravel 4.1渴望加载与约束的嵌套关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图通过约束来获得加载嵌套的关系。每个人似乎都提供了一个渴望加载嵌套关系的例子:

I am trying to get Eager-Loading nested relationships, with constraints, to work. Everyone seems to be giving the same example of eager-loading nested relationships:

$users = User::with('posts.comments')->get();

我想要做的是让所有用户与给定ID的帖子相关。但是在同一时间,我也想得到与该帖子相关的评论。

What I want to do instead is get all the the Users related to a post of a given id. But at the same time, I also want to get the comments associated with that post.

在4.1中,我实现后者,我可以做:

In 4.1, I to achieve the latter, I could do:

$comments = Comment::whereHas('post', function($query) { $query->whereId(1); })->get();

有没有办法结婚这两个并约束一个嵌套关系?

Is there a way to marry this two and constrain a nested relationship?

推荐答案

实际上发现它比想象的要简单得多。

Actually found it a lot simpler than thought.

给定这些模型:

class User extends \Eloquent {

    public function posts()
    {
        return $this->hasMany('Post');
    }

    public function comments()
    {
        return $this->hasManyThrough('Comment', 'Post');
    }       

}

class Post extends \Eloquent {

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function comments()
    {
        return $this->hasMany('Comment');
    }       

}

class Comment extends \Eloquent {

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

}

然后我们可以提取一个用户有一个给定的帖子如下:

We can then fetch a user that has a given post like so:

$userId = 2; $postId = 5;
$user =  User::with(['comments' => function($q) use($postId) { $q->where('post_id', $postId); }])->find($userId);

使用get()时不会工作,因为它不会限制用户只有相关的给给定的职位。但是这是可以的,因为我们只对post_id $ postId的单个帖子感兴趣。由于帖子属于一个,只有一个用户,我们不用担心其他用户。因此,我们可以使用find()或first()获取实际结果。

This won't work when using get() as it DOES NOT constrain the users to only those related to the given post. But this is OK since we are only interested in a single post of post_id $postId. Since a post belongsTo one and only one user, we needn't worry about the other users. We could therefore use find() or first() to get the actual results.

此外,中间关系即'post'自动返回,我们可以得到通过执行以下操作,而不必像以前的答案一样使用额外的'with':

Also, the 'middle' relationship i.e. 'post' is automatically returned and we can get it by doing the following without having to use an extra 'with' as suggested in previous answer:

var_dump($user->posts);

这篇关于Laravel 4.1渴望加载与约束的嵌套关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆