0

помогите решить проблему. Есть две таблицы 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
];

Table

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

template.

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

При первом добавлении компаний сохранение происходит нормально, но когда я пробую изменить список компаний или сохранить без изменений, получаю сообщение об ошибке.

Могу ли я изменить список компании с помощью _ids или необходимо писать свой код?

Ошибки и Debugs:

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

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

При редактировании (не первом), patchEntity вместо того что бы найти записи в таблице companies и модифицировать их, пытаеться создать новую сущность. Вот фрагменты скриншотов debug($businessDepartment) и страница с ошибкой

Спасибо, надеюсь на вашу помощь.

1
  • зачем вы отдельным запросом грузите компании? сразу ->contain(['Companies' => function($q){ $q->find('list')->where(....) }])
    – teran
    5 фев 2019 в 9:18

1 ответ 1

0

Может кому-то пригодится!

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

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.