Laravel 5.3许多与众不同的关系模式 [英] Laravel 5.3 Many to many relationship with same model

查看:206
本文介绍了Laravel 5.3许多与众不同的关系模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用CRM,我有一个用户模型,它可以与其他用户有许多关系,也可以通过数据透视表定义一种类型的关系。

I am working on a CRM where I have a User model which can have many to many relationships with other User's and a type of relationship which is defined through the pivot table.

例如:

Tim - > Tom(同事)

Tim -> Tom ( co-worker )

Tim - > Steve(家庭成员)

Tim -> Steve ( family member )

Tim - > Jon(邻居)

Tim -> Jon ( neighbors )

在我的用户模型中,我有这个我使用的数据透视表中的user1_id和user2_id作为外键:

In my User model I have this where I'm using user1_id and user2_id from the pivot table as foreign keys:

public function relationships ()
{
    return $this->belongsToMany(User::class,null,'user1_id','user2_id')->withTimestamps()->withPivot('type');
}

哪个方向正常。所以如果我这样称呼:

Which works fine in one direction. So if I call this:

User::find($timsID)->relationships;

正如预期的那样,我会让汤姆·史蒂夫和乔恩成为结果。现在,如果我在这个查询中使用了Tom的ID,Tim将不会返回一个关系,因为当在user2中存储了Tom的ID时,它正在搜索user1_id。

That works as expected and I'll get Tom Steve and Jon as results. Now, if I were to use Tom's ID in that query instead, Tim won't return as a relationship since it's searching on user1_id when Tom's ID is stored in user2.

如果有一个外键匹配,是否有解决方案来拉出记录?我不想为每个关系存储2条记录。

Is there a solution to pull the records if there's a match from either foreign key? I don't want to have to store 2 records for each relationship.

推荐答案

我会假设我理解你想要什么去做。 Laravel的关系在双向工作。在你的情况下,你只定义了一个方向,但是要在两个方向上使用它。清除我的意思

I will assume I sort of understood what you want to do. Relationships in Laravel work in both directions. In your case, you have only defined ONE direction, but want to use it in both directions. To clear what I mean

public function peopleIKnow() {
    return $this->belongsToMany(User::class,null,'user1_id','user2_id')->withTimestamps()->withPivot('type');
}

public function peopleWhoKnowMe() {
    return $this->belongsToMany(User::class,null,'user2_id','user1_id')->withTimestamps()->withPivot('type');
}

这样你就有了双向关系。你可以在这个想法的基础上获得你想要的东西。

This way you have two way relationship. You can build on top of this idea to get what you want.

这篇关于Laravel 5.3许多与众不同的关系模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆