Nested eloquent relationship

49 views Asked by At

I just started my first laravel project today and stumbled upon this confusing situation, I intended to use eloquent relationship instead of manually joining tables on query. So here it goes...

I have 3 tables which are users , tbl_instruments_taught , tbl_instruments

users table does not hold any of the table's ID,

tbl_instruments_taught - holds the id of user and intruments

Note: user can teach multiple instruments

Now, I implemented a hasOne on my other result set but I dont think hasOne works on this one.
I read about belongsToMany but as I try implement it, it seems like every minute, it gets confusing.

Any idea?

1

There are 1 answers

2
Milena Grygier On

I think you are looking for pivot table and relation many to many. You have users table, instruments table (user has many instruments and one instrument could belong to many users) and user_instruments pivot table. Here db model: enter image description here

And then add belongsToMany relationship in User and Instrument model (with specified pivot table). Like so:

//IN USER MODEL
public function instruments()
{
  return $this->belongsToMany('App\Models\Instruments', 'users_instruments', 'user_id', 'instrument_id');
}

//IN INSTRUMENT MODEL
public function users()
{
  return $this->belongsToMany('App\Models\Users', 'users_instruments', 'insrument_id', 'user_id');
}

Now you can reach instruments/users data through laravel relations/eager loading.