How to compare two fields/columns in a condition?

巧了我就是萌 提交于 2019-12-02 00:12:38

Whenever encountering query problems, check what queries are actually being generated (for example using DebugKit). Unless being an expression object, the right hand side of a condition will always be bound as a parameter, ie you're comparing against a string literal:

Pupils.school_id = 'Schools.id'

Generally for proper auto quoting compatibility, column names should be identifier expressions. While the left hand side will automatically be handled properly, the right hand side would require to be handled manually.

In your specific case you could easily utilize QueryExpression::equalFields(), which is ment for exactly what you're trying to do, comparing fields/columns:

->where(function (\Cake\Database\Expression\QueryExpression $exp, \Cake\ORM\Query $query) {
    return $exp->equalFields('Pupils.school_id', 'Schools.id');
})

It's also possible to create identifier expressions manually by simply instantiating them:

->where([
    'Pupils.school_id' => new \Cake\Database\Expression\IdentifierExpression('Schools.id')
])

or as of CakePHP 3.6 via the Query::identifier() method:

->where([
    'Pupils.school_id' => $query->identifier('Schools.id')
])

And finally you could also always pass a single string value, which is basically inserted into the query as raw SQL, however in that case the identifiers will not be subject to automatic identifier quoting:

->where([
    'Pupils.school_id = Schools.id'
])

See also

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!