mapawa
mapawa

Reputation: 191

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

groups

users_in_groups

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?

Upvotes: 1

Views: 253

Answers (1)

John Lobo
John Lobo

Reputation: 15319

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

Upvotes: 1

Related Questions