坚持雄辩的关系 - 枢轴和多态关系

时间:2016-03-12 22:46:53

标签: laravel eloquent schema laravel-5.2 relationships

您好我仍然试图获取属于这两个模型之间的枢轴的用户的所有评论。我似乎无法绕过它或我的数据库架构可能是完全错误的。无论如何我会喜欢一些帮助。

目前我的模型看起来像这样:

user.php的

class User extends Model 
{
    // Grab all the beers that this user has checked in to his personal profile
    public function beers()
    {
        return $this->belongsToMany('App\Beer')->withTimestamps()->withPivot('rating', 'description');
    }
}

Beer.php(枢轴关系)

class Beer extends Model
{
    // polymorphic relationship grab all comments that belong to this beer
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

Comment.php(设置为多态)

class Comment extends Model
{
    public function commentable()
    {
        return $this->morphTo();
    }

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

此处的代码抓取属于啤酒枢轴记录的所有评论。这非常合适,因为$ user->啤酒会考虑到我们正在处理特定的用户配置文件,并且只能从特定的$ user中查找数据透视记录。

$user = User::find($id);

@foreach($user->beers as $beer)
    @foreach($beer->comments as $comment)
    {{ $comment }}
    @endforeach
@endforeach

不幸的是,评论关系仅查看评论表中的commentable_id和commentable_type,并没有考虑当前的user_id(我们当前正在查看的个人资料),所以当我查看具有相同beer_user的用户的另一个个人资料时在他的个人资料中的枢轴组合,同样的评论也显示在那里。

如何调用我的Beer.php模型的评论关系,以便我也考虑到user_id?显然我已经在我的评论表中添加了一个user_id。我以前试过这个问题,但是我希望通过更详细一点这次人们现在可以帮助我,我也知道如何最终制定这个问题好一点。

数据库:

enter image description here

1 个答案:

答案 0 :(得分:1)

在这个特定的代码示例中,我只使用对用户id具有约束的预先加载:

$user = User::with(['beers', 'beers.comments' => function ($query) use ($id) {
    $query->whereHas('user', function ($query) use ($id) {
        $query->where('id', $id);
    });
}])->find($id);

@foreach($user->beers as $beer)
    @foreach($beer->comments as $comment)
    {{ $comment }}
    @endforeach
@endforeach

此热切加载限制仅在您提前拥有用户ID时才有效。

但是,想象一下,您无法限制急切加载或查询以获取评论。您仍然可以在事实之后过滤评论集合:

@foreach($user->beers as $beer)
    @foreach($beer->comments->where('user_id', $user->id) as $comment)
    {{ $comment }}
    @endforeach
@endforeach