具有一对多关系的多个表(Laravel)
Multiple tables with one to many relationship(Laravel)
我有 3 个 table,即 A、B 和 C。
他们3个都需要用到一个音符table(即A有很多音符,一个音符属于A,剩下2个table同理)。
所以我又创建了 3 个 table:A_note、B_note 和 C_note(如此处所述:multiple tables need one to many relationship)。
有没有办法对这些 tables(A_note, B_note 和 C_note) 进行 CRUD 操作,类似于我们处理 pivot [=25 的方式=] 在多对多关系中?
请提出前进的方向。
您应该为此使用 polymorphic
关系。它允许多个模型使用单个 table.
Have a look at the documentation here
在您的特定情况下,您的每个 table 都会引用一个 noteable_id
列和一个 noteable_type
。
noteable_id
将包含 (A/B/C)
模型的 ID。
noteable_type
将包含模型的字符串名称 (A/B/C)
。
(A/B/C)
模型现在将获得一个新属性:
/**
* (A/B/C) Model(s)
*/
public function notes()
{
return $this->morphMany('App\Notes', 'noteable');
}
并且 note
模型将针对用于识别您的 polymorphic ids and types
:
的属性名称启动它的多态属性
/**
* Note Model
*/
public function noteable()
{
return $this->morphTo();
}
现在您可以简单地在 (A/B/C)
模型上调用 ->noteable
,它们都共享 1 table,而不需要每个 [=41] 的另一个枢轴 table =].
我有 3 个 table,即 A、B 和 C。
他们3个都需要用到一个音符table(即A有很多音符,一个音符属于A,剩下2个table同理)。
所以我又创建了 3 个 table:A_note、B_note 和 C_note(如此处所述:multiple tables need one to many relationship)。
有没有办法对这些 tables(A_note, B_note 和 C_note) 进行 CRUD 操作,类似于我们处理 pivot [=25 的方式=] 在多对多关系中?
请提出前进的方向。
您应该为此使用 polymorphic
关系。它允许多个模型使用单个 table.
Have a look at the documentation here
在您的特定情况下,您的每个 table 都会引用一个 noteable_id
列和一个 noteable_type
。
noteable_id
将包含 (A/B/C)
模型的 ID。
noteable_type
将包含模型的字符串名称 (A/B/C)
。
(A/B/C)
模型现在将获得一个新属性:
/**
* (A/B/C) Model(s)
*/
public function notes()
{
return $this->morphMany('App\Notes', 'noteable');
}
并且 note
模型将针对用于识别您的 polymorphic ids and types
:
/**
* Note Model
*/
public function noteable()
{
return $this->morphTo();
}
现在您可以简单地在 (A/B/C)
模型上调用 ->noteable
,它们都共享 1 table,而不需要每个 [=41] 的另一个枢轴 table =].