Laravel 10 - hasOne with a pivot table

75 Views Asked by At

I have 3 tables:

users

  • id
  • name

place

  • id
  • name

place_waiter_pivot

  • user_id
  • place_id

One place can have many users (waiters), but a user can be assigned only to one place (also user doesn't have to be a waiter, so he will not belong to any place in this case).

So far I have this relations written, but they don't work. What am I doing wrong here?

Place model:

public function waiters(): HasManyThrough
    {
        return $this->hasManyThrough(User::class, 'place_waiter_pivot');
    }

User model:

public function waiter(): HasOneThrough
    {
        return $this->hasOneThrough(Place::class, 'place_waiter_pivot');
    }
1

There are 1 best solutions below

0
On

Well, your usage may not be appropiate for the scenario you want. So, using belongsToMany should resolve your problem.

You can try to change your code like this:

class Place extends Model
    {
        public function waiters(): BelongsToMany
        {
            return $this->belongsToMany(User::class, 'place_waiter_pivot', 'place_id', 'user_id');
        }
    }

And in your user model:

class User extends Model
{
    public function places(): BelongsToMany
    {
        return $this->belongsToMany(Place::class, 'place_waiter_pivot', 'user_id', 'place_id');
    }
}