0

I'm having difficulty using Cakephp 3 patchEntity to save associated models. The models involved are summarized here

My UsersTempTable

 public function initialize(array $config)
{
    $this->table('users_temp');
    $this->displayField('name');
    $this->primaryKey('id');
    $this->addBehavior('Timestamp');
    $this->hasOne( 'UsersExtraTemp', [
        'foreignKey' => 'user_id'
    ]);

}

Then my UsersExtraTempTable

public function initialize(array $config)
    {
        $this->table('users_extra_temp');
        $this->displayField('id');
        $this->primaryKey('id');
        $this->belongsTo('UsersTemp', [
            'foreignKey' => 'user_id',
            'joinType' => 'INNER'
        ]);
    }
    public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->existsIn(['user_id'], 'UsersTemp'));
        return $rules;
    }

Mi function to save the data:

   $user = $this->newEntity();
   $user = $this->patchEntity($user, $this->request->data, [
              'associated' => ['UsersTemp.UsersExtraTemp']
           ]);
   $this->save( $user, ['associated' => ['UsersExtraTemp']] );

And my array of data print by $this->debug()

(
    [name] => name
    [lastname] => lastname
    [email] => email@email.com
    [password] => password
    [passwordConfirm] => repeatPassord
    [UsersExtraTemp] => Array
        (
            [google_token] => sjskdasdadk2
        )

)

I get a row created for user_temp in the database but nothing for the one users_extra that I'm expecting. Any idea what I'm doing wrong please?

ndm
  • 59,784
  • 9
  • 71
  • 110
rcastellanosm
  • 57
  • 3
  • 5

1 Answers1

0

Given that $this refers to UsersTempTable, the associated option for patchEntity() should not contain that name, as this would suggest that UsersTempTable is associated with UsersTempTable, which is not the case.

The option should look exactly the same as in the save() call, ie

$user = $this->patchEntity($user, $this->request->data, [
    'associated' => ['UsersExtraTemp']
]);

Also in the data you should use the proper property name for the association, which, in case of a hasOne association, is the singular, underscored variant of the association name, ie users_extra_temp

(
    // ...

    [users_extra_temp] => Array
        (
            [google_token] => sjskdasdadk2
        )

)

And last but not least, make sure that the property name is defined in the UsersTemp entities $_accessible property

class UsersTemp extends Entity
{
    // ...

    protected $_accessible = [
        // ...
        'users_extra_temp' => true,
        // ...
    ];

    // ...
}

See also

ndm
  • 59,784
  • 9
  • 71
  • 110