Sunday, March 19, 2017

Laravel 5.4. How to merge 3 tables with relationships

I have big trouble with merging tables. I would like to merge the data of all users (from tables below) and see results in view (HTML table)

The user has more than one instrument and more than one friend. I used example from Stackoverflow to create working friend relationship but i don't know how to merge and show instruments of users's friends.

Table users: (id, first_name, last_name, city, address)
Table friends: (id, user_id, friend_id)
Table instruments (id, name)
Table instrument_user (id, user_id, instrument_id)

User Model:

public function friendsOfMine()
{
  return $this->belongsToMany('App\User', 'friends', 'user_id', 'friend_id');
}

public function friendOf()
{
  return $this->belongsToMany('App\User', 'friends', 'friend_id', 'user_id');
}

public function friends()
{
  return $this->friendsOfMine()->get()->merge($this->friendOf()->get());
}

Friend and Instrument models are now empty. I tried to use merge() more than one time in the same line and doesn't work...



via hamunaptra

Advertisement