CakePHP v3: how to get patchEntity to update associations in request data

I am using patchEntity()

hasMany associations to update and it works great. My problem is not related to the data being stored in the DB. My problem is that the association data stored in the entity variable is not syncing ...

Note that in the method below, I have to do the second get()

after saving to RE-read the data from the DB. If I remove this, the next view shows the stale association data as patchEntity updates the foreign keys, but the actual association object is still the previous one (since save).

I wish I could make two DB queries in a row. Is this the intended behavior? Is there a better way to do this?

public function edit($id = null)
{
    //1//////////////////////////////////////////
    $screen = $this->Screens->get($id, [
        'contain' => ['Blocks'=>['Datasources'=>['Agencies']]] 
    ]);

    if ($this->request->is(['patch', 'post', 'put'])) {

        $screen = $this->Screens->patchEntity(  $screen, 
                                                $this->request->data, 
                                                [
                                                    'associated'=>['Blocks.Datasources']
                                                ]
                                            );
        if ($this->Screens->save($screen)) {

            //2//////////////////////////////////////////
            #get the UPDATED properties... specifically, the associations don't get updated automatically by patchEntity above
            $screen = $this->Screens->get($id, [
                'contain' => ['Blocks'=>['Datasources'=>['Agencies']]]
            ]);

            $this->Flash->success('The screen has been saved.');
        } else {
            $this->Flash->error('The screen could not be saved. Please, try again.');
        }
    }

    $this->set(compact('screen'));
}

      

+3


source to share


1 answer


There is of course no way to avoid the second request. Even if the framework has implemented this functionality, it will need to use a different query to find associations with the most recent data.



So while it seems wasteful, this is the only way to do it.

+1


source







All Articles