我如何在蛋糕php中的子查询中使用主查询值作为过滤器

时间:2019-10-08 16:03:54

标签: sql cakephp orm cakephp-3.0

如何将其转换为使用子查询中主查询值的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']); 

1 个答案:

答案 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()示例)。

另请参见