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