Laravel 7 Eloquent: 评论属于用户属于多组

Laravel 7 Eloquent: Comment BelongsTo User belongsToMany Groups

我正在尝试建立以下关系:

评论 (user_id) ->belongTo 用户 ->belongsToMany -> 群组

(枢轴:group_user)

我希望能够获取与评论关联的所有组:Comment::find(i)->groups。 还有 Comment::wherehas('groups')Comment::Where(groups in [1,3])

我一直在看 https://github.com/staudenmeir/eloquent-has-many-deep#belongsto 但无法使其按预期工作。

 public function groups()
    {

         return $this->hasManyDeep('App\Group', ['group_user', 'App\User']);
    }

Laravel 7

这可能对您有所帮助

//'tables1','tables2','tables3' are relations in USER model & 'COL 7' is column of table 3

$x=USER::where('status','active')->with('tables1','tables2','tables3')->whereHas('tables3', function($q)
                {
                    $q->where('COL 7',"US");

                })->get();
                dd($x);

来自 github 讨论:

class Comment extends Model
{
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function groups()
    {
        return $this->hasManyDeep(
            Group::class
            [User::class, 'group_user'],
            ['id'],
            ['user_id']
        );
    }
}

很有魅力!