0

I need to ask you guys, how can I merge this two Laravel relations?

database table 'usuarios' = stands for users.

I need to gather this both relations in a single way to check if they are friends or not, with a single query.

Model User.php

 public function friends()
{
    return $this->belongsToMany('App\User', 'friends', 'user1_id', 'user2_id')
        ->withPivot('is_friend')
        ->wherePivot('is_friend', '=', '1');
}

public function friendsOf()
{
    // hasMany
    return $this->belongsToMany('App\User', 'friends', 'user2_id', 'user1_id')
        ->withPivot('is_friend')
        ->wherePivot('is_friend', '=', '1');
}

Database: 

usuarios
----------
id
username
name



friends
----------
id
user1_id
user2_id -> int - reference on -> usuarios.id
is_friend -> boolean

I've followed a tutorial on internet and tried the following, but still had no success.

// accessor allowing you call $user->friends
public function getFriendsAttribute()
{
    if ( ! array_key_exists('friends', $this->relations)) $this->loadFriends();

    return $this->getRelation('friends');
}

protected function loadFriends()
{
    if ( ! array_key_exists('friends', $this->relations))
    {
        $friends = $this->mergeFriends();

        $this->setRelation('friends', $friends);
    }
}

protected function mergeFriends()
{
    return $this->friends->merge($this->friendOf);
}

THANK YOU VERY MUCH Link to tutorial: Friendship system with Laravel : Many to Many relationship

Community
  • 1
  • 1
JCC
  • 43
  • 1
  • 9
  • It looks like piece of code of mine, but there's slight difference - mine used `friendOf` and `friendsOfMine`, thus `$this->friends->merge...` didn't collide with the `getFriendsAttribute` accessor. That said, rename `friends` relation. – Jarek Tkaczyk Jul 08 '15 at 15:43
  • Yes, I've followed a tutorial, but I dont know what I need to do. Rename friends() to? Thank you – JCC Jul 08 '15 at 18:04
  • Link that tutorial. And rename it to `friendsOfMine` like above. – Jarek Tkaczyk Jul 08 '15 at 18:15

0 Answers0