-1

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

}
Salines
  • 5,674
  • 3
  • 25
  • 50
MOHA
  • 122
  • 1
  • 10
  • Instead of creating duplicates, edit your original question and fill it with proper information. http://stackoverflow.com/questions/34369905/save-associated-in-cakephp-3-0-not-working – ndm Dec 20 '15 at 14:14

1 Answers1

0

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))
...
Carl0s1z
  • 4,683
  • 7
  • 32
  • 47
Salines
  • 5,674
  • 3
  • 25
  • 50
  • First level associations are being merged by default, using associated is only necessary for deeper levels, or for disabling/restricting merging of associations. – ndm Dec 20 '15 at 15:57
  • I am also facing the same issue. Above reply is not working please help me out. – Lakhan Jul 31 '17 at 15:24