我喜欢创建多态关系,我不确定我是否在我的情况下做正确的方式?
我有一个description_groups
表,它属于多个descriptions
对于横向多态关系,表如customers
和orders
可以有多个descriptions
这是我想到的数据库模式:
description_groups
:
+----+----------------+
| id | name |
+----+----------------+
| 1 | Stock Movement |
+----+----------------+
descriptions
table:
description_groups
属于下面列出的多个descriptions
+----+----------------------+--------+
| id | description_group_id | name |
+----+----------------------+--------+
| 1 | 1 | Name 1 |
| 2 | 1 | Name 2 |
| 3 | 1 | Name 3 |
| 4 | 1 | Name 4 |
+----+----------------------+--------+
使用polymorphic_table
表,我可以定义哪个表和条目可以有描述。表名应该是什么?例如:
+----+----------------+------------+----------+
| id | description_id | table_name | table_id |
+----+----------------+------------+----------+
| 1 | 4 | customers | 2 |
| 2 | 2 | orders | 10 |
+----+----------------+------------+----------+
customers table
:
+----+-----------------+
| id | name |
+----+-----------------+
| 1 | Customer Name 1 |
| 2 | Customer Name 2 |
| 3 | Customer Name 3 |
+----+-----------------+
这意味着Customer Name 2
有Name 4
条目的描述,属于Stock Movement
条目。
Laravel内置了对多态关系的支持,你可以在这里找到更多。
我真的不明白你为什么要这样设置模式,但是这是我要做的,这样客户和订单就可以有描述。
descriptions ( <id>, name, content, describable_type, describable_id )
customers (<id>, name)
orders (<id>, items)
注意descriable_type
是一个字符串,descriable_id
是一个无符号整数。
接下来,您必须设置关系,如文档中所述(注意注释,它告诉您它们属于哪个模型文件):
// In AppDescription
public function describable()
{
return $this->morphTo();
}
// In AppCustomer
public function descriptions()
{
return $this->morphMany('AppDescription', 'describable');
}
// In AppOrders
public function descriptions()
{
return $this->morphMany('AppDescription', 'describable');
}
现在,这里有一件事Laravel文档没有提到;一对一的多态关系的创建方式与一对一的正常关系相同,而一对多的多态关系的创建方式与一对多的正常关系相同……(只要把morphTo
看作是多态的belongsTo
)
所以使用这个:
// be sure to set the correct $guarded access before using create()
$description = Description::create(['name' => 'Name', 'content' =>'Lorem Ispum";
$customer = Customer::create(['name' => 'Customer 1']);
$customer->describable()->associate($description);
$customer->save();