HasMany - 保存关联数据

HasMany - save association data

我需要帮助。我有两个表 business_departmentscompanies 关联类型 hasMany.

我需要修改部门中的公司列表。代码是通过 bake 生成的,然后我修改了它。

控制器。

$businessDepartment = $this->BusinessDepartments->get($id, [
    'contain' => ['Companies']
]);
$companies = $this->BusinessDepartments->Companies->find('list')->where([
    'Companies.active' => true, 
    'Companies.type IS NOT' => 'service', 
    'OR' => [
        'business_department_id IS NULL',
        'business_department_id' => $id
    ]
])->distinct('Companies.id');
if ($this->request->is(['patch', 'post', 'put'])) {
    debug($this->request->getData());
    $businessDepartment = $this->BusinessDepartments->patchEntity($businessDepartment, $this->request->getData(), ['associated' => ['Companies']]);
    debug($businessDepartment);
    if ($this->BusinessDepartments->save($businessDepartment)) {
        $this->Flash->success(__('The business department has been saved.'));

        return $this->redirect(['action' => 'index']);
    }
    $this->Flash->error(__('The business department could not be saved. Please, try again.'));
}
$this->set(compact('businessDepartment', 'companies'));

实体。

protected $_accessible = [
    'name' => true,
    'companies' => true
];

Table

$this->hasMany('Companies', [
    'foreignKey' => 'business_department_id',
    // Tried it
    /*'dependent' => true,
    'cascadeCallbacks' => true,
    'saveStrategy' => 'replace'*/
]);

模板.

echo $this->Form->control('companies._ids', ['options' => $companies, 'multiple' => true, 'class' => 'multiple-find']);

添加公司的第一次保存是成功的,但是当我尝试修改公司列表时(如果尝试不做任何更改而保存)我得到错误。

我可以通过 *._ids 保存还是需要为其制作自定义代码?

以下debug($this->request->getData())

[
    'name' => 'Office',
    'companies' => [
        '_ids' => [
            (int) 0 => '21',
            (int) 1 => '29'
        ]
    ]
]

但是在 patchEntity 之后,patchEntity 没有搜索公司并更改其中的 business_department_id 字段,而是尝试创建新公司并显示错误。下面是截图的片段。 debug($businessDepartment) and screenshot page

谢谢。希望快点回答

说不定有人会派上用场!

you have validation errors in your company related data, thats why you cant save it, if you want to just use _ids as save try clearing companies field in your $businessDepartment i.e.

$businessDepartment->unsetProperty('companies');

before patchEntity

Graziel