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

Al_*_*Al_ 12 php orm laravel eloquent laravel-4

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

数据透视表模式

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

pivot table seeder(这定义了两个'友谊',用户'1'属于user'id,其中user_1在user_id中指定,而第二个用户1在friend id中列出):

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

    );
Run Code Online (Sandbox Code Playgroud)

用户模型

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

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

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

foreach(Auth::user()->friends as $i) {
    var_dump($i->id);
}
Run Code Online (Sandbox Code Playgroud)

这将返回值"3"但不是预期的4.我明白为什么会发生这种情况(因为user_id不是friend_id)但是如何让它返回属于用户的所有朋友的集合(即所有友谊),而不管连接的哪一端(user_id或friend_id)用户是?

小智 16

而不是创建两个记录使用新功能.

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 )
Run Code Online (Sandbox Code Playgroud)

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

  • 自我引用多对多关系的一个很好的例子,也许这些名称实现有点奇怪,但基本原则仍然存在.+1先生. (3认同)
  • 这需要分别调用 Friends() 和 theFriends() 来获取所有朋友的集合。这并不是一个很好的解决方案,尤其是当您考虑到双重 SQL 查询时。 (2认同)