Laravel - 数据透视表上的附加关系

时间:2023-04-10
本文介绍了Laravel - 数据透视表上的附加关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个带有 2 个键的常规数据透视表.但是,我还有第三列,我想在其中存储具有一对多关系的不同键.这可能吗?

I have a regular pivot table with 2 keys. However, I also have a 3rd column where I want to store a different key with a one to many relationship. Is this possible to have?

示例:

数据透视表:
组织 1 |组织 2 |关系类型
1 |2 |1
1 |3 |2

Pivot table:
Organization 1 | Organization 2 | Relation type
1 | 2 | 1
1 | 3 | 2

在这种情况下,组织编号 1 与组织编号 2 存在关系,关系类型为编号 1.组织编号 1 也与组织编号 3 存在关系,关系类型为 2.

In this case organization number 1 has a relation with organization number 2 with the relation type being number 1. Organization number 1 also has a relation with organization number 3 with relation type 2.

现在是我的问题,如何在数据透视表上设置额外的一对多关系?

Now is my question, how do I set up that additional one to many relationship on the pivot table?

推荐答案

这里是三元关系.您是说组织 A 与组织 B 和关系类型相关.这是一个非常罕见的用例,因为在绝大多数情况下,三元关系可以简化为二元关系.您需要对您的数据模型进行非常深入的检查,以确定您的案例是否可以简化,但假设不能,这是我的建议.

What you have here is a ternary relationship. You are saying that an organisation A relates with an organisation B and a relationship type. This is a very uncommon use case because in the vast majority of cases ternary relationships can be simplified to binary ones. You need a very deep inspection of your data model to determine whether your case can be simplified, but assuming that it can't here's my suggestions.

值得检查雄辩的文档,特别是在为此定义自定义中间表模型.请注意,这需要 Laravel 5.4+ 才能工作.

It's worth checking the eloquent docs in particular under Defining Custom Intermediate Table Models for this. Note that this requires Laravel 5.4+ to work.

以下应该有效:

class OrganisationOrganisationLink extends Pivot {
    public relationType() {
          return $this->belongsTo(RelationType::class); //You need to specify the foreign key correctly as a 2nd parameter
    }
}

然后在您的原始模型中:

Then in your original model:

class Organisation extends Model {
    public relatedOrganisation() {
        return $this->belongsToMany(self::class)->using(OrganisationOrganisationLink::class); 
    }
}

然后在实际使用它时,您可以例如做:

Then when making practical use of this you can e.g. do:

$organisation = Organisation::with('relatedOrganisation')->first();
echo "Got ".$organisation->name." which relates to "
     .$organisation->relatedOrganisation->first()->name 
     ." with relationship type "       
     $organisation->relatedOrganisation->first()->pivot->relationshipType()->value('name'); 

当然,我假设的领域可能不存在,但希望你能明白.

Of course the fields I've assumed may not exist but hopefully you get the idea.

这篇关于Laravel - 数据透视表上的附加关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:更新 Laravel 5.3 中的一对多关系 下一篇:Laravel 'like' 查询与 MongoDB 连接

相关文章