Search code examples
laraveleloquenteloquent-relationship

Laravel Eloquent belongsToMany only fetches one result


My belongsToMany function only returns a single element when it should return all of them.

This is my table structure (simplified):

users

  • id
  • ...

groups

  • id
  • ...

users_in_groups

  • id
  • user_id
  • group_id

This is my function:


    public function getUsers(): BelongsToMany
    {
        return $this->belongsToMany(
            UserDao::class,
            'users_in_groups',  //table
            'id',               //foreignPivotKey
            "user_id"           //relatedPivotKey
        );
    }

I call the getResults() method on the result and even then it only has a single object in the items array.

The table is well filled when I manually look it up. What am I missing?


Solution

  • Look like issue is with $foreignPivotKey and $relatedPivotKey

    public function belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null,
                                  $parentKey = null, $relatedKey = null, $relation = null)
    

    So your relationship should be

     public function getUsers(): BelongsToMany
        {
            return $this->belongsToMany(
                UserDao::class,
                'users_in_groups',
                "group_id" ,    
                'user_id',               
                       
            );
        }
    

    Also both