Laravel-数据透视表上的其他关系 [英] Laravel - Additional relationship on a pivot table

查看:71
本文介绍了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
    }
}

然后使用原始模型:

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-数据透视表上的其他关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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