2015-08-15 128 views
0

比方说你有用户和朋友架构Laravel和雄辩 - 查询“朋友”关系

user: 
    - id 
    - username 

friends: 
    - id 
    - user_id 
    - friend_id 

A“友谊”由具有两个相互记录来确定。让我们说,如果它只是一种单向关系,这是一个未决的请求。所以在朋友表:

user_id: 5 | friend_id: 6 
user_id: 6 | friend_id 5 

用户模型中,你将不得不:

public function friends() 
    { 
     return $this->belongsToMany(self::class,'friends','user_id','friend_id')->withTimestamps(); 
    } 

然而,这并不是故事的全部,因为这不检查的存在相互关系。

你会如何设置? friends()方法是否应该负责进一步查询数据?或者这种方法是否合适,以及想要获得相互友谊的实例,应该追加一个查询范围?例如

$this->user->friends->mutual() 

OR

$this->user->friends->pending() 

回答

0

截止了搞清楚了这一点基于this answer。但是,我将merge()功能更改为intersect(),因为我不使用approved标志来确定友谊是相互的天气。我只使用两种关系的存在。

所以在我的情况。的关系是:

public function myFriends() 
{ 
    return $this->belongsToMany(self::class,'friends','user_id','friend_id')->withTimestamps(); 
} 

public function friendsOf() 
{ 
    return $this->belongsToMany(self::class,'friends','friend_id','user_id')->withTimestamps(); 
} 

而另一个逻辑是:

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)) $this->setRelation('friends', $this->mergeFriends()); 
} 

protected function mergeFriends() 
{ 
    return $this->myFriends->intersect($this->friendsOf); 
}