Save associated in cakephp 3 not working

时间秒杀一切 提交于 2019-12-25 17:18:24

问题


My save associated in cakephp3 (3.1.5 and 3.0) is not working.

users table relation withuser_profiles table is hasOne and user_profiles table relation with users table is belongsTo.

When I want to save a user record with associated user_profile record, user record saves in users table but no record is saved in associated table user_profiles. I have no error in error.log


Entities

for both of them =>

protected $_accessible = [
  * => true
];

Users Controller

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:


Your 'associated' => ['UserProfiles'] is on wrong place. add him to newEntity() or patchEntity();

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

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


来源:https://stackoverflow.com/questions/34378456/save-associated-in-cakephp-3-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!