CakePHP 3:保存关联模型失败

时间:2015-07-27 19:54:01

标签: php cakephp cakephp-3.0

我在使用Cakephp 3 patchEntity来保存相关模型时遇到了困难。所涉及的模型总结在这里

我的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'
    ]);

}

然后我的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函数保存数据:

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

我的数据数据打印为$ this-> debug()

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

)

我在数据库中为user_temp创建了一行,但对于我期待的那个users_extra却没有。知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

鉴于$this引用UsersTempTableassociated的{​​{1}}选项不应包含该名称,因为这表明patchEntity()UsersTempTable相关联UsersTempTable,情况并非如此。

该选项应与save()调用中的选项完全相同,即

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

同样在数据中,您应该为关联使用适当的属性名称,如果是hasOne关联,则是关联名称的单数,下划线变体,即users_extra_temp

(
    // ...

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

)

最后但并非最不重要的是,确保在UsersTemp实体$_accessible属性

中定义属性名称
class UsersTemp extends Entity
{
    // ...

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

    // ...
}

另见