2016-08-19 42 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