我需要问你们,我怎样才能合并这两个Laravel关系?
数据库表' usuarios' =代表用户。
我需要通过单一查询以单一方式收集这两种关系以检查他们是否是朋友。
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
我已经按照互联网上的教程尝试了以下内容,但仍然没有成功。
// 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);
}
非常感谢你 链接到教程:Friendship system with Laravel : Many to Many relationship