我喜欢创造多态关系,我不确定我的情况是否正确?
我有description_groups
表,它属于许多descriptions
关于laravel多态关系,customers
和orders
等表可以有很多descriptions
以下是我提出的数据库架构:
description_groups
表:
+----+----------------+
| id | name |
+----+----------------+
| 1 | Stock Movement |
+----+----------------+
descriptions
表:
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
条目。
答案 0 :(得分:1)
Laravel已经建立了对多态关系的支持,您可以找到更多here。
我真的不明白你为什么以你的方式设置你的架构,但是我这样做是为了让客户和订单可以有描述。
descriptions ( <id>, name, content, describable_type, describable_id )
customers (<id>, name)
orders (<id>, items)
请注意,descriable_type
是一个字符串,descriable_id
是无符号整数。
接下来,您将必须设置关系,如文档中所述(请注意告诉您属于哪个模型文件的注释):
// In App\Description
public function describable()
{
return $this->morphTo();
}
// In App\Customer
public function descriptions()
{
return $this->morphMany('App\Description', 'describable');
}
// In App\Orders
public function descriptions()
{
return $this->morphMany('App\Description', '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();