2016-08-19 44 views
0

我喜欢创建多态关系,我不确定在我的情况下我是否正确地做出了选择?多态关系设置?

我有description_groups表,它是属于许多descriptions

在涉及到laravel多态性关系表如customersorders可以有很多descriptions

这里是我想出了数据库模式:

description_groups表:

+----+----------------+ 
| id | name   | 
+----+----------------+ 
| 1 | Stock Movement | 
+----+----------------+ 

descriptions表:

description_groups是属于下面使用

+----+----------------------+--------+ 
| id | description_group_id | name | 
+----+----------------------+--------+ 
| 1 |     1 | Name 1 | 
| 2 |     1 | Name 2 | 
| 3 |     1 | Name 3 | 
| 4 |     1 | Name 4 | 
+----+----------------------+--------+ 

polymorphic_table表我可以定义哪些表和条目可能说明中列出许多descriptions。表名应该是什么?例如:

+----+----------------+------------+----------+ 
| 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 2Name 4条目说明这是属于Stock Movement条目。

+0

表的名字不应该是一个表,它应该是代表表中的模型的路径。 'App \ Customer'和'App \ Order'很好。此外,不应该被称为'table_name',而是'entity_name'和'table_id'也应该是'entity_id'。更清洁,更直接,遵循Laravel的设计杂注。 – Ohgodwhy

+0

@Ohgodwhy谢谢你,随时发布你的答案。 'description'和'description_groups'看起来很好吗? –

回答

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(); 
+0

非常感谢@Extrakun。这非常有帮助。我不明白为什么当我们有'description.id'时我们需要'descriable_id'。 “说明”表就像预定义列表,它与“description_groups”表链接。所以基本上如果用户从一个组中选择'股票移动',然后显示一个描述列表。用户从描述列表中选择任何一个,然后保存到数据透视表中。合理? –

+0

“可描述的”并不是指描述,而是描述的内容。所以它指的是客户或您的案例中的订单。 describeable_id是客户或其所属订单的ID,而describeable_type存储它是客户还是订单。 – Extrakun