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