gpt4 book ai didi

php - Laravel 多对多自引用表只能以一种方式工作

转载 作者:行者123 更新时间:2023-12-03 01:15:59 25 4
gpt4 key购买 nike

我已经设置了如下关系和模型:

数据透视表架构

Schema::create('friend_user', function(Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('friend_id')->unsigned();
$table->timestamps();
});

数据透视表播种器(这定义了用户“1”所属的两个“好友关系”,其中一个是在 user_id 中指定了用户 1,另一个是在好友 ID 中列出了用户 1):

    $friend_user = array(
array(
'id' => 1,
'user_id' => 1,
'friend_id' => 3,
),
array(
'id' => 2,
'user_id' => 4,
'friend_id' => 1,
),

);

用户模型

public function friends()
{
return $this->belongsToMany('User', 'friend_user', 'user_id', 'friend_id');
}

这是 Taylor Otwell 的建议:https://github.com/laravel/framework/issues/441

这一切都有效,但是当我运行以下命令时,我只得到一个结果:

foreach(Auth::user()->friends as $i) {
var_dump($i->id);
}

这将返回值“3”,但不是预期的 4。我理解为什么会发生这种情况(因为 user_id 不是friend_id),但是如何才能返回属于用户的所有 friend (即所有友谊)的集合,无论连接的哪一端(user_id 或friend_id)用户是?

最佳答案

使用新函数而不是创建两条记录。

public function friends()
{
return $this->belongsToMany('User', 'friend_user', 'user_id', 'friend_id');
}

// Same table, self referencing, but change the key order
public function theFriends()
{
return $this->belongsToMany('User', 'friend_user', 'friend_id', 'user_id');
}

//You can then call opposite record(s) using:
foreach( Auth::user()->theFriends as $theFriends )

我在我的项目中使用了这种方法,这样我就可以更好地分离来组织结果。

关于php - Laravel 多对多自引用表只能以一种方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17567305/

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