我在cakephp3(3.1.5和3.0)中保存的保存无效。
与users
表的 user_profiles
表关系是hasOne,与user_profiles
表的users
表关系是belongsTo。
当我想保存具有关联user_profile记录的用户记录时,用户记录保存在users
表中,但没有记录保存在关联表user_profiles
中。我在error.log中没有错误
对于他们两个=>
protected $_accessible = [
* => true
];
public function add()
{
$data = [
'email' => 'example@test.com',
'username' => 'Example',
'password' => '123456789',
'user_profile' => [
'first_name' => 'John',
'last_name' => 'Smit',
'phone' => '123456798'
]
];
$entity = $this->Users->newEntity();
$entity = $this->Users->patchEntity($entity, $data);
if ($this->Users->save($entity, [
'associated' => ['UserProfiles']
])) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
答案 0 :(得分:0)
您的'associated' => ['UserProfiles']
位置错误。将他添加到newEntity()
或patchEntity()
;
...
$entity = $this->Users->patchEntity($entity, $data, [
'associated' => ['UserProfiles']
]);
if ($this->Users->save($entity))
...