HasMany-保存关联数据

时间:2019-01-28 07:39:18

标签: php cakephp cakephp-3.0

我需要帮助。我有两个关联类型为business_departments的表companieshasMany

我需要修改部门中的公司列表。在修改之后,通过 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
];

$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)screenshot page

谢谢。我希望能尽快得到答案。

1 个答案:

答案 0 :(得分:0)

也许有人会派上用场!

  

与公司相关的数据中存在验证错误,这就是为什么   无法保存,如果您只想使用_ids作为保存,请尝试清除   companies中的$businessDepartment字段,即

$businessDepartment->unsetProperty('companies');
     

patchEntity之前

     

Graziel

相关问题