1
votes

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' => '[email protected]',
        '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
Instead of creating duplicates, edit your original question and fill it with proper information. stackoverflow.com/questions/34369905/… - ndm

1 Answers

0
votes

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))
...