MDebus
January 7, 2025, 10:05am
1
I am encountering the following issue in CakePHP 5.1.4:
For certain database fields, I have defined a custom database type.
In queries, I would like to use a WHERE clause like this:
$this->MyTable->find()
->where(['customField' => true]);
When i debug that, this query properly triggers the toStatement()
and toDatabase()
methods in the custom database type.
However, when I add a condition involving an associated table, it doesn’t work:
$this->MyTable->find()
->contain(['OtherTable'])
->where(['OtherTable.customField' => true]);
Both fields are defined as custom db type in Model->getSchema() method like this:
if ($schema->hasColumn($column)) {
$schema->setColumnType($column, 'MyCustomType');
}
What am I doing wrong, or is this a bug?
I am on CakePHP 5.1.4 and can’t reproduce your problem.
I tested it with the CakePHP provided EnumType, but should still be the same. This is my callstack how it gets to the toDatabase
call.
This is with the given query:
$query = $this->FtpDomains->find()
->contain(['FtpLoginData', 'RepositoryBranches'])
->where(['FtpLoginData.connection_type' => ConnectionType::SFTP]);
so should be the same as yours.
MDebus
January 8, 2025, 8:47am
3
"I tried it today with another sample script, and it worked. Now I found my mistake.
It is important to first add associations with contain()
and then the where
clause. That was correct in my sample code but not in the real code.
This works:
$query = $this->MyModel->find('all')
->contain(['OtherModel'])
->where($conditions)
and this don’t work:
$query = $this->MyModel->find('all')
->where($conditions)
->contain(['OtherModel'])
I hope you understand why the order is important here
MDebus
January 8, 2025, 10:10am
5
Sure… But the transformation with toDatabase() is triggered only after the $query->all() command, not when adding the condition.
Defining contain
first seems logical overall.