坚持 eloquent 关系 - 枢轴和多态关系

Stuck on eloquent relationships - pivot and polymorphic relationship

你好,我一直在尝试获取属于某个用户的所有评论,其中一个枢轴位于这两个模型之间。我似乎无法理解它,或者我的数据库模式可能完全错误。无论如何,我希望得到一些帮助。

目前我的模型是这样的:

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->beers 考虑到我们正在处理特定的用户配置文件,并且只从特定的 $user.

中找到数据透视记录
$user = User::find($id);

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

不幸的是,评论关系仅从评论table中查看commentable_id和commentable_type而没有考虑当前的user_id(我们的个人资料当前正在查看)所以当我查看另一个用户的个人资料时,他的个人资料上有相同的 beer_user 数据透视组合,同样的评论也会出现在那里。

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

数据库:

在这个特定的代码示例中,我将只使用预加载并限制用户 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 时,这种预先加载约束才会起作用。

想象一下,但是,您无法限制预先加载或查询以获取评论。您仍然可以在事后过滤评论 Collection:

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