CakePHP 4.1保存的AboutTo关联不起作用

问题描述

我有两个数据库表-UsersUserTypes,其中Users一个外键user_type_id。 下面是他们的样板模型代码

Entity/User.PHP

class User extends Entity {
    protected $_accessible = [
        'id' => true,'email' => true,'password' => true,'name' => true,'user_type_id' => true,// added this as an experiment Now,but I shouldn't need it if I understand correctly
        'user_type' => true
    ];
}

Entity/UserType.PHP

class UserType extends Entity {
    protected $_accessible = [
        'id' => true,'users' => true,];
}

Table/UsersTable.PHP

class UsersTable extends Table
{
public function initialize(array $config): void
{
    parent::initialize($config);

    $this->setTable('users');
    $this->setdisplayField('name');
    $this->setPrimaryKey('id');

    $this->belongsTo('UserTypes',[
        'joinType' => 'INNER'
    ]);
}


public function validationDefault(Validator $validator): Validator
{
    $validator
        ->integer('id')
        ->allowEmptyString('id',null,'create');

    $validator
        ->email('email')
        ->requirePresence('email','create')
        ->notEmptyString('email');

    $validator
        ->scalar('password')
        ->maxLength('password',255)
        ->requirePresence('password','create')
        ->notEmptyString('password');

    $validator
        ->scalar('name')
        ->maxLength('name',255)
        ->allowEmptyString('name');

    return $validator;
}

public function buildrules(RulesChecker $rules): RulesChecker
{
    $rules->add($rules->isUnique(['email']));
    $rules->add($rules->existsIn(['user_type_id'],'UserTypes'));

    return $rules;
}
}

Table/UserTypestable.PHP

class UserTypestable extends Table
{
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('user_types');
        $this->setdisplayField('name');
        $this->setPrimaryKey('id');
        $this->hasMany('Users');
    }

    public function validationDefault(Validator $validator): Validator
    {
        $validator
            ->integer('id')
            ->allowEmptyString('id','create');

        $validator
            ->scalar('name')
            ->requirePresence('name','create')
            ->notEmptyString('name');

        return $validator;
    }
}

现在的问题是,我似乎无法将记录的user_type_id字段保存在数据库users表中。 为了重现该问题,我在UsersController.PHP中创建了以下简单操作:

public function testAdd()
{
    $testUser = $this->Users->newEmptyEntity();
    $testUser->name = "Test";
    $testUser->email = "test@test.com";
    $testUser->password = "secret";
    $testUser->user_type = $this->Users->UserTypes->get(1); // this exists and I've verified get() finds it correctly
    $this->Users->save($testUser);
}

其结果为sqlSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails,尝试的查询INSERT INTO users (email,password,name) VALUES (:c0,:c1,:c2),显然没有必要的user_type_id字段。

我尝试更改不会失败的现有用户用户类型(因为已经满足FK约束),但是也没有发生更改。

我也尝试过$this->Users->save($testUser,['associated' => ['UserTypes']]);,它对产生的INSERT SQL查询没有任何改变。

所以我的问题是,如何插入和更新用户实体的外键字段?

----编辑----

debug(get_class($this->Users))之前运行save()会产生:

APP/Controller/UsersController.PHP (line 270)
'App\Model\Table\UsersTable'

debug($testUser)之前运行save()会产生:

APP/Controller/UsersController.PHP (line 271)
object(App\Model\Entity\User) id:0 {
'name' => 'Test'
'email' => 'test@test.com'
'password' => '$2y$10$13nmS6Iag3seqkae9L.M0Ow.xV0Tasd/y9xnu12xX9yIozsXNLEnO'
'user_type' => object(App\Model\Entity\UserType) id:1 {
'id' => (int) 1
'name' => 'Full admin'
'[new]' => false
'[accessible]' => [
'id' => true,]
'[dirty]' => [
]
'[original]' => [
]
'[virtual]' => [
]
'[hasErrors]' => false
'[errors]' => [
]
'[invalid]' => [
]
'[repository]' => 'UserTypes'
protected _accessible => [
'id' => true,]
protected _fields => [
'id' => (int) 1,'name' => 'Full admin',]
protected _original => [
]
protected _hidden => [
]
protected _virtual => [
]
protected _dirty => [
]
protected _accessors => [
'App\Model\Entity\User' => [
'set' => [
'password' => '_setPassword','Password' => '_setPassword','name' => '','email' => '','user_type' => '',],]
protected _new => false
protected _errors => [
]
protected _invalid => [
]
protected _registryAlias => 'UserTypes'
}
'[new]' => true
'[accessible]' => [
'id' => true,'created' => true,'modified' => true,'user_type' => true
]
'[dirty]' => [
'name' => true,'user_type' => true,]
'[original]' => [
]
'[virtual]' => [
]
'[hasErrors]' => false
'[errors]' => [
]
'[invalid]' => [
]
'[repository]' => 'Users'
protected _accessible => [
'id' => true,'user_type' => true
]
protected _hidden => [
(int) 0 => 'password',]
protected _fields => [
'name' => 'Test','email' => 'test@test.com','password' => '$2y$10$13nmS6Iag3seqkau9L.M0Ow.xV0Tasd/y9XNe12xX9yIozsXNLEnO','user_type' => object(App\Model\Entity\UserType) id: 1 {},]
protected _original => [
]
protected _virtual => [
]
protected _dirty => [
'name' => true,]
protected _accessors => [
'App\Model\Entity\User' => [
'set' => [
'password' => '_setPassword',]
protected _new => true
protected _errors => [
]
protected _invalid => [
]
protected _registryAlias => 'Users'
}

解决方法

写@ndm的评论作为答案,以便任何人在这里遇到同样的问题。原来在添加user_types数据库表之前,我的ORM模式已被缓存。清除/tmp/cache/models对我有用。当心缓存!

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...