如何将其转换为使用子查询中主查询值的orm 这是我的SQL子查询
(select ups.username from users as ups where ups.id=student_id) as StudentName
我的主查询从内部联接获取student_id
这是我的Orm子查询
->select([
'StudentName'=>'Users.username'])
->where(['Users.id'=>'students.studentid']);
运行查询StudentName
时显示为空白,但是如果我手动设置该值,它将返回结果
->select([
'StudentName'=>'Users.username'])
->where(['Users.id'=>'55']);
答案 0 :(得分:0)
使用key => value
语法时,除非是表达式对象,否则右边的值将始终受绑定/转义的约束。因此,您的条件会将Students.student_id
绑定为文字字符串,或者可能绑定为整数,即您最终会遇到如下SQL:
WHERE Users.id = 'Students.student_id'
或
WHERE Users.id = 0
要么传递\Cake\Database\Expression\IdentifierExpression
对象,例如:
->where(['Users.id' => $mainQuery->identifier('Students.student_id')])
或在较旧的CakePHP版本中:
->where(['Users.id' => new \Cake\Database\Expression\IdentifierExpression('Students.student_id')])
或使用表达式构建器,该构建器支持比较字段:
->where(function(\Cake\Database\Expression\QueryExpression $exp) {
return $exp->equalFields('Users.id', 'Students.student_id');
})
高级条件文档中有您的用例示例(请参见exists()
示例)。
另请参见