問題描述
我有一個帶有 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 - 數據透視表上的附加關系的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!