I have two DB tables - Users
and UserTypes
where Users
has a foreign key user_type_id
.
Below is their boilerplate model code.
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,
'name' => 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', null, 'create');
$validator
->scalar('name')
->requirePresence('name', 'create')
->notEmptyString('name');
return $validator;
}
}
Now the problem is that I don't seem to be able to save the user_type_id
field of a record in the users
table of the database.
To reproduce the issue, I have created a the following simple action in UsersController.php
:
public function testAdd()
{
$testUser = $this->Users->newEmptyEntity();
$testUser->name = "Test";
$testUser->email = "[email protected]";
$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);
}
The result of this is SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
and the attempted query is INSERT INTO users (email, password, name) VALUES (:c0, :c1, :c2)
which clearly doesn't have the necessary user_type_id
field.
I have tried changing an existing user's user type which doesn't fail (since the FK constraint is already satisfied) but no change occurs either.
I have also tried $this->Users->save($testUser, ['associated' => ['UserTypes']]);
which changed nothing for the resulting INSERT
SQL query.
So my question is, how can I insert and update the foreign key field of my User entity?
---- EDIT ----
Running debug(get_class($this->Users))
just before save()
yields:
APP/Controller/UsersController.php (line 270)
'App\Model\Table\UsersTable'
And running debug($testUser)
just before save()
yields:
APP/Controller/UsersController.php (line 271)
object(App\Model\Entity\User) id:0 {
'name' => 'Test'
'email' => '[email protected]'
'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,
'name' => true,
'users' => true,
]
'[dirty]' => [
]
'[original]' => [
]
'[virtual]' => [
]
'[hasErrors]' => false
'[errors]' => [
]
'[invalid]' => [
]
'[repository]' => 'UserTypes'
protected _accessible => [
'id' => true,
'name' => true,
'users' => 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,
'email' => true,
'password' => true,
'name' => true,
'created' => true,
'modified' => true,
'user_type_id' => true,
'user_type' => true
]
'[dirty]' => [
'name' => true,
'email' => true,
'password' => true,
'user_type' => true,
]
'[original]' => [
]
'[virtual]' => [
]
'[hasErrors]' => false
'[errors]' => [
]
'[invalid]' => [
]
'[repository]' => 'Users'
protected _accessible => [
'id' => true,
'email' => true,
'password' => true,
'name' => true,
'created' => true,
'modified' => true,
'user_type_id' => true,
'user_type' => true
]
protected _hidden => [
(int) 0 => 'password',
]
protected _fields => [
'name' => 'Test',
'email' => '[email protected]',
'password' => '$2y$10$13nmS6Iag3seqkau9L.M0Ow.xV0Tasd/y9XNe12xX9yIozsXNLEnO',
'user_type' => object(App\Model\Entity\UserType) id: 1 {},
]
protected _original => [
]
protected _virtual => [
]
protected _dirty => [
'name' => true,
'email' => true,
'password' => true,
'user_type' => true,
]
protected _accessors => [
'App\Model\Entity\User' => [
'set' => [
'password' => '_setPassword',
'Password' => '_setPassword',
'name' => '',
'email' => '',
'user_type' => '',
],
],
]
protected _new => true
protected _errors => [
]
protected _invalid => [
]
protected _registryAlias => 'Users'
}
Writing @ndm's comment as an answer for the sake of anyone who ends up here with the same problem. Turns out my ORM schema was cached before I added the user_types
DB table. Clearing /tmp/cache/models
worked for me. Beware the cache!