UserMastersTable.php:
$this->hasOne('PersonMasters', [
'className' => 'PersonMasters',
'foreign_key' => 'user_master_id',
'dependent' => true
]);
控制器代码:
public function editUser($id) {
$countryOptions = $this->Countries->find('list')->select(array('id', 'name'));
$this->set(compact('countryOptions'));
$user_detail = $this->UserMasters->get($id, ['contain' => ['PersonMasters']]);
$this->set('user_detail', $user_detail);
if ($this->request->is('post'))
{
$user=$this->UserMasters->newEntity();
$user = $this->UserMasters->patchEntity($user,$this->request->data,['associated'=> ['PersonMasters']]);
$this->UserMasters->save($user,['associated'=> ['PersonMasters']]);
}
}
它不会更新数据。每次在user_masters
和person_masters
表中保存新记录时。那么如何更新user_masters
和person_masters
?
如果我在.ctp
视图文件中设置一个包含user_masters
id
的隐藏字段,那么它只更新user_masters
条记录,并在person_masters
中添加新记录表
我已在每个实体中分配' * '=true
,包括UserMasters
。它仍然无法正常工作。
那么如何更新cakephp3中的user_masters
和关联表。
答案 0 :(得分:3)
问题中的问题是创建并修补了新实体,发布的数据不包含主键值,因此它始终是插入。
修复方法是修补$user_detail
对象(已包含现有主键值,因为它已从数据库中读出),然后保存:
$user = $this->UserMasters->patchEntity(
$user_detail,
$this->request->data,
['associated' => ['PersonMasters']]
);
$this->UserMasters->save($user,['associated'=> ['PersonMasters']]);