【问题标题】:CakePHP 3: Save Associated Model FailCakePHP 3:保存关联模型失败
【发布时间】:2015-07-27 19:54:01
【问题描述】:

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

我的用户临时表

 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 创建一行。请知道我做错了什么吗?

【问题讨论】:

  • 那么,你保存过程中的$thisUsersTempTable?
  • 是的@ndm .. 保存的过程是模型本身而不是控制器

标签: php cakephp cakephp-3.0


【解决方案1】:

鉴于$this 指的是UsersTempTablepatchEntity()associated 选项不应包含该名称,因为这表明UsersTempTableUsersTempTable 相关联,但事实并非如此。

该选项应该看起来与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,
        // ...
    ];

    // ...
}

另见

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 2011-08-01
    • 2013-09-24
    • 1970-01-01
    相关资源
    最近更新 更多