在cakephp 3中保存关联不起作用

时间:2015-12-20 06:11:19

标签: cakephp cakephp-3.0

我在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.'));
    }

}

1 个答案:

答案 0 :(得分:0)

您的'associated' => ['UserProfiles']位置错误。将他添加到newEntity()patchEntity();

...
$entity = $this->Users->patchEntity($entity, $data, [
        'associated' => ['UserProfiles']
    ]);

    if ($this->Users->save($entity))
...