栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Laravel的友谊系统:多对多关系

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Laravel的友谊系统:多对多关系

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;


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/468801.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号