CakePHP v3:如何让 patchEntity 更新请求数据中的关联
CakePHP v3: How to get patchEntity to update associations in request data
我正在使用 patchEntity()
来更新 hasMany 关联并且它工作正常。我的问题与数据库中保存的数据无关。我的问题是存储在实体变量中的关联数据不同步...
请注意,在下面的方法中,我必须在保存后执行第二次 get()
以从数据库重新读取数据。如果我删除它,下一个视图将显示陈旧的关联数据,因为 patchEntity 更新了外键,但实际的关联对象仍然是前一个(保存之前的)。
我希望有一种方法可以避免连续进行两个数据库查询。这是预期的行为吗?有更好的方法吗?
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'));
}
第二次查询当然是没办法避免的。即使框架实现了该功能,它也需要使用另一个查询来查找与最新数据的关联。
虽然看起来很浪费,但这是唯一的方法。
我正在使用 patchEntity()
来更新 hasMany 关联并且它工作正常。我的问题与数据库中保存的数据无关。我的问题是存储在实体变量中的关联数据不同步...
请注意,在下面的方法中,我必须在保存后执行第二次 get()
以从数据库重新读取数据。如果我删除它,下一个视图将显示陈旧的关联数据,因为 patchEntity 更新了外键,但实际的关联对象仍然是前一个(保存之前的)。
我希望有一种方法可以避免连续进行两个数据库查询。这是预期的行为吗?有更好的方法吗?
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'));
}
第二次查询当然是没办法避免的。即使框架实现了该功能,它也需要使用另一个查询来查找与最新数据的关联。
虽然看起来很浪费,但这是唯一的方法。