gpt4 book ai didi

php - Laravel 的友谊系统 : Many to Many relationship

转载 作者:IT王子 更新时间:2023-10-29 00:05:33 26 4
gpt4 key购买 nike

我正在尝试使用 Laravel 创建一个友谊系统(我正在从它开始),但我被关系所阻碍。事情是这样的:有一张 Users 表和一张 Friends 表,其中包含以下列:

friends: id, user_id, friend_id, accepted.

它看起来像多对多,所以这是我在用户类上设置的:

class User extends Eloquent {
function friends()
{
return $this->belongsToMany('User');
}
}

但是当我尝试:

$friends = User::find($id)->friends()->get()

我有这个错误:

Base table or view not found: 1146 Table 'base.user_user' doesn't exist

我想获取用户的好友列表,无论用户是发送还是收到邀请。因此,用户可以根据 user_id 或 friend_id,然后我根据该列检索其他用户的数据。

有什么想法吗?谢谢!

编辑:这是我使用的代码:

$usersWithFriends = User::with('friendsOfMine', 'friendOf')->get();
$user = User::find(Auth::id())->friends;

foreach($user as $item) {
echo $item->first()->pivot->accepted;
}

最佳答案

tldr;您需要 2 个反向关系才能使其工作,请检查下面的设置和使用


首先是错误 - 你的关系应该是这样的:

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 started
function 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->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->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;

关于php - Laravel 的友谊系统 : Many to Many relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25049753/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com