1

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?

mapawa
  • 179
  • 1
  • 4
  • 16
  • 1
    return $this->belongsToMany( UserDao::class, 'users_in_groups', //table 'user_id', //foreignPivotKey "group_id" //relatedPivotKey ); – John Lobo Jun 14 '21 at 10:11
  • i think even you can remove both ids since its matching naming convention – John Lobo Jun 14 '21 at 10:15
  • @JohnLobo That did almost work, I just had to change the order of "user_id" and "group_id". Thanks a lot! Post that as an answer and I will mark it as the solution. – mapawa Jun 14 '21 at 10:16
  • @JohnLobo No I can't, because its not really "users" and "groups" but domain-specific terms I didn't want to confuse you with ;) – mapawa Jun 14 '21 at 10:17
  • oaky.np :)have a great day – John Lobo Jun 14 '21 at 10:17

1 Answers1

1

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

John Lobo
  • 14,355
  • 2
  • 10
  • 20
  • Almost! But "group_id" has to come before "user_id" – mapawa Jun 14 '21 at 10:19
  • 1
    updated my answer. i think if you are in group model then it should similar i guess. since i always follow table naming convention .so very rarely using extra params – John Lobo Jun 14 '21 at 10:20