一对多关系的表(Laravel) [英] Multiple tables with one to many relationship(Laravel)
问题描述
所有3个表都需要使用一个notes表(即A有很多注释,一个注释属于A.同样的说,剩下的2个表)。
所以我创建了3个表:A_note,B_note和C_note(如下所述:多个表需要一对多关系)。
有没有办法在这些表(A_note,B_note和C_note)上进行类似于以多对多关系处理数据透视表的方式进行CRUD操作?
请建议一条路。
多态性
关系为此。它允许多个模型使用单个表。
在你的具体情况下,每个表都会引用一个 noteable_id
列和一个 noteable_type
。
noteable_id
将包含(A / B / C)
model。
noteable_type
将包含模型的字符串名称(A / B / C)
。
(A / B / C)
模型现在将获得一个新的属性:
/ **
*(A / B / C)模型
* /
public function notes()
{
return $ this-> morphMany('App \Notes','noteable');
}
而笔记
模型将根据用于标识您的多态标识和类型
的属性名称启动它的多态属性:
/ **
*注意模型
* /
public function noteable()
{
return $ this-> morphTo();
}
现在您可以简单地调用 - > noteable
(A / B / C)模型,并且它们都共享1个表,而不需要为每个表使用另一个数据透视表。
I have 3 tables namely A, B and C.
All 3 of them need to make use of a notes table(i.e. A has many notes and a note belongs to A. The same follows for remaining 2 tables).
So I created 3 more tables: A_note, B_note and C_note(as mentioned here: multiple tables need one to many relationship).
Is there a way to do CRUD operations on these tables(A_note, B_note and C_note) similar to the way we handle pivot table in many-to-many relationship?
Please suggest a way forward.
You should be using polymorphic
relationships for this. It allows multiple models to make use of a single table.
Have a look at the documentation here
In your particular case, each of your tables would reference a noteable_id
column and a noteable_type
.
The noteable_id
will contain the id of the (A/B/C)
model.
The noteable_type
will contain the string name of the model (A/B/C)
.
The (A/B/C)
models will now get a new attribute:
/**
* (A/B/C) Model(s)
*/
public function notes()
{
return $this->morphMany('App\Notes', 'noteable');
}
And the note
model will initiate it's polymorphic properties against the attribute name used to identify your polymorphic ids and types
:
/**
* Note Model
*/
public function noteable()
{
return $this->morphTo();
}
Now you can simply call ->noteable
on the (A/B/C)
models, and they all share 1 table without the need of another pivot table for each table.
这篇关于一对多关系的表(Laravel)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!