Laravel多对多自引用表只有一种工作方式


Laravel Many to many self referencing table only works one way

我已经建立了如下关系和模型:

透视表模式

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,另一个是用户1在friend id中列出):

    $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),但我如何才能让它返回属于用户的所有朋友的集合(即所有友谊),而不管用户是连接的哪一端(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 )

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

使用此

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

在这种情况下,每个关系得到一个查询和一条记录