0

我在多对多关系中有员工和复合体。我使用烘焙控制台为员工和复合体表生成模型、控制器……。我的问题是:-因为我的 BD 中有“complexes_employees”表,我是否也必须为这个表烘焙模型和控制器,或者 cakePHP 能够知道它包含员工和复合体的两个外键。

第二个问题:-如何将我的数据保存在这三个表中。对于我的应用程序,我必须为每个 Complex 保存员工。

// 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

谢谢你帮助我

4

1 回答 1

2

我是否还必须为此表烘焙模型和控制器?

不,CakePHP 将使用抽象Table类。但是,如果您需要有关此关系的额外信息,则需要创建一个连接模型。检查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

于 2016-01-14T14:59:49.090 回答