2016-01-11 45 views
0

我有僱員和複雜的多對多關係。我使用了 烘焙控制檯爲Employees和Complexes表生成模型,控制器...。 我的問題是: - 因爲我有在我的BD表「complexes_employees」,我也必須烘烤型號 和控制器這個表也可以cakephP能夠知道它包含 僱員的兩個外鍵和配合。cakePHP 3以多對多關係保存數據

第二個問題: - 如何將數據保存在這三個表中。對於我的應用程序,我必須爲每個組合員工保存員工 。

// Employees Controller 
public function addEmpPerComplex($id_complex){ 
$emp = $this->Employees->newEntity(); 
if ($this->request->is('post')) { 
$employee = $this->Employees->patchEntity($employee, $this->request->data, ['associated'=>['Complexes._joinData']]); 
//here I need to insert the record that contains the employee data in Employees Table 
// then I need to insert in "complexes_employees" the ID of Complex sended in parametre of this function and the ID of the new Employee 

謝謝你幫我

回答

1

我一定要烤也爲此表模型和控制器?

不,CakePHP將使用摘要類。但是,如果您需要此關係的額外信息,則您需要創建一個加入模型。檢查http://book.cakephp.org/3.0/en/orm/associations.html#using-the-through-option

如何將我的數據保存在這三個表中?

只要你的數據具有相關實體的ID,它會自動保存兩種實體和關係:

$data = [ 
    //employee data, 
    'complexes' => [ 
     ['id' => $id_complex] 
    ] 
] 

$this->Employees->patchEntity($employee, $data, [ 
    'associated' => ['Complexes'] 
]); 

/* 
Saves both the new Employee and the relation 
(employeed id and complex id in complexes_employees) 
*/ 
$this->Employees->save($employee); 

欲瞭解更多信息:http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-belongstomany-associations

+0

非常感謝,不,我不要在我的關聯中沒有其他字段「complexes_employees」,因此不需要爲此表創建模型和控制器。爲了保存代碼,我會嘗試你告訴我希望它能起作用。再次,謝謝你的時間和你的幫助:) – Hanane