且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-30 20:58:14

使用新函数代替创建两条记录.

Instead of creating two records use a new function.

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 )

我在我的项目中使用了这种方法,因此我可以更好地分离组织结果.

I used this approach in my project so I can have better separation for organizing the results.