Мне нужна помощь.У меня есть две таблицы business_departments
и companies
с типом связи hasMany
.
. Мне нужно изменить список компаний, состоящий из отдела.Код был сгенерирован с помощью bake , после чего я изменил его.
Controller.
$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'));
Entity.
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 вместо поиска компаний и изменения в них полей business_department_id patchEntity пытается создать новые компании и отображает ошибку.Ниже приведен фрагмент скриншота.debug($businessDepartment)
и страница скриншота
Спасибо.Надеюсь на быстрый ответ.