Deleting Records From Associated Table With PatchEntity in CakePHP

感情迁移 提交于 2019-12-08 07:02:31

问题


I have a CakePHP model where a Job hasmany Employees and an Employee belongsTo a Job. The View I use to edit both Jobs and Employees is a Job view. Here is code from my Job Controller:

   $job = $this->Jobs->get($id, [
        'contain' => ['Employees']
    ]);

    if ($this->request->is(['patch', 'post', 'put'])) {
        $req = $this->request->data;
        $job = $this->Jobs->patchEntity($job, $req, [
            'validate' => false,
            'associated' => ['Employees']
        ]);
        $saveResult = $this->Jobs->save($job, [
            'validate' => false,
            'associated' => ['Employees']
        ]);

$this->request->data looks like this:

'employees' =>[
      0 => [
        'id' => 1,
         ... etc ...

When I add employees, $this->request->data has more array elements and the patch adds the new records to the employees table.

When I delete employees, $this->request->data has fewer array elements. But the patch doesn't delete any records. (I am fixing the array ordering with array_values when the data comes back).

Is there a way I can get the patch to delete records when there are fewer records in the request?

If not, what's the best way to do the deletes?


回答1:


I don't know if I completely get your question/wanted result, but from your line

Is there a way I can get the patch to delete records when there are fewer records in the request?

i read it as you want to replace the "old" associated data with the new associated data in a current post request.

A hasMany association's has 'saveStrategy' => 'append' as default (https://api.cakephp.org/3.4/source-class-Cake.ORM.Association.HasMany.html#84-89). (since version 3.1 i think)

You can change saveStrategy to replace like:

$this->hasMany('Employees', [
    'className' => 'Employees',
    'foreignKey' => 'employee_id',
    'saveStrategy' => 'replace'
]);

When saveStrategy is set to replace, only associated data in the current post/patchEntity will be associated to the current models record on save. Foreign key of existing linked associated data will be set to null.



来源:https://stackoverflow.com/questions/45294313/deleting-records-from-associated-table-with-patchentity-in-cakephp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!