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


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

数据透视表模式

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

数据透视表播种器(这定义了两个'友谊',用户'1'属于一个用户1,在user_id中指定用户1,第二个用户1在朋友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)用户是?


895
2017-07-10 09:39


起源

你在播种机上有2个关系,一个用于两个不同的用户。那么你的函数只会为每个用户返回一个结果? - Laurence
是的,但第二条记录上的friend_id是用户1的id,因此两个条目都定义了友谊,只是一个用户发起了一个,另一个用户发起了另一个用户。我正试图找出如何返回友谊,无论他们输入系统的顺序如何。 - Al_
哦 - 我现在明白了......或许在你结交朋友时插入两条记录?友谊的“每一种方式”都有一个?这将是最简单的。 - Laurence
这是我的备份计划,我希望有一种更清洁的方式来做到这一点 - Al_
你是怎么处理@Al_的? - Mike


答案:


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

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 )

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


15
2017-07-21 01:53



这将需要分别调用friends()和theFriends()来获取所有朋友的集合。几乎没有一个非常好的解决方案,特别是一旦你考虑了双SQL查询。 - Mike
是的 - 这非常适合实施 followers但对朋友来说却不那么...... - Ben Gotow
自我引用多对多关系的一个很好的例子,也许这些名称实现有点奇怪,但基本原则仍然存在。 +1先生。 - Dylan Pierce
是的好例子虽然名字很糟糕。混乱。 - AndrewMcLagan


用这个

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

在这种情况下,您将获得每个关系的一个查询和一个记录


-2
2017-07-13 11:43



当你试图吸引另一方的朋友时,你总是回归自己,因为它使用了friend_id - cleanunicorn