cakePHP 3 以多对多关系保存数据

cakePHP 3 save data in Many to Many relationship

我在多对多 relationship.I 中有员工和复合体 烘烤控制台以生成模型、控制器... 用于员工和复合体 tables。 我的问题是: -既然我的BD里有table"complexes_employees",我是不是也要烤模型 和这个 Table 的控制器或者 cakePHP 能够知道它包含 Employees 和 Complexes 的两个外键。

第二个问题: -如何在这三个 table 中保存我的数据。对于我的应用程序,我必须拯救员工 每个复合体 .

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

谢谢你帮助我

我还需要为这个 Table 烘焙模型和控制器吗?

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