tldr; 您需要2个反向关系才能使其正常工作,请在下面检查SETUP和USAGE
首先是 错误 -这是您的关系应如何显示:
function friends(){ return $this->belongsToMany('User', 'friends', 'user_id', 'friend_id') // if you want to rely on accepted field, then add this: ->wherePivot('accepted', '=', 1);}然后它将正常工作:
$user->friends; // collection of User models, returns the same as:$user->friends()->get();
设定
但是, 您希望该关系以两种方式起作用。Eloquent不提供这种关系,因此 您可以使用2个反向关系并合并结果 :
// friendship that I startedfunction friendsOfMine(){ return $this->belongsToMany('User', 'friends', 'user_id', 'friend_id') ->wherePivot('accepted', '=', 1) // to filter only accepted ->withPivot('accepted'); // or to fetch accepted value}// friendship that I was invited to function friendOf(){ return $this->belongsToMany('User', 'friends', 'friend_id', 'user_id') ->wherePivot('accepted', '=', 1) ->withPivot('accepted');}// accessor allowing you call $user->friendspublic 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->friendsOfMine->merge($this->friendOf);}用法
通过这种设置,您可以执行以下操作:
// access all friends$user->friends; // collection of unique User model instances// access friends a user invited$user->friendsOfMine; // collection// access friends that a user was invited by$user->friendOf; // collection// and eager load all friends with 2 queries$usersWithFriends = User::with('friendsOfMine', 'friendOf')->get();// then$users->first()->friends; // collection// Check the accepted value:$user->friends->first()->pivot->accepted;


