Search code examples
laraveleloquenthas-manyhas-and-belongs-to-many

Laravel 7 Eloquent: Comment BelongsTo User belongsToMany Groups


I am trying to setup the following relationsship:

Comment (user_id) ->belongTo User ->belongsToMany ->Groups

(Pivot: group_user)

I want to be able to fetch all groups associated with the comment with: Comment::find(i)->groups. Also Comment::wherehas('groups') and Comment::Where(groups in [1,3])

I've been looking at https://github.com/staudenmeir/eloquent-has-many-deep#belongsto But can't get it to work as intended.

 public function groups()
    {

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

Laravel 7


Solution

  • From github discussion:

    class Comment extends Model
    {
        use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
    
        public function groups()
        {
            return $this->hasManyDeep(
                Group::class
                [User::class, 'group_user'],
                ['id'],
                ['user_id']
            );
        }
    }
    

    Works like a charm!