cakePHP 3将数据保存在多对多关系中

时间:2016-01-11 20:44:49

标签: cakephp-3.x

我有很多关系中的员工和复合体。我使用过 烘焙控制台为Employees和Complexes表生成模型,控制器...... 我的问题是: - 因为我已经在我的BD桌子" complex_employees",我是否还需要烘烤模型 和这个表的控制器或cakePHP能够知道它包含 员工和综合体的两个外键。

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

// 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 个答案:

答案 0 :(得分: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