简体   繁体   English

Laravel查询构建器不适用于子查询中的where子句

[英]Laravel query builder doesn't work with where clause in subquery

I have a query like this: 我有这样的查询:

$q = \DB::table(\DB::raw('('.
    \DB::table('table1')
         ->where('field1', 1)->toSQL()
.') AS rs'));

dd($q->get()); // return []

Despite why I have to use this approach, when I remove the where clause it returns all the records correctly, but nothing when using where() . 尽管为什么我必须使用这种方法,但是当我删除where子句时,它会正确返回所有记录,但是在使用where()时却什么也没有。

I'm sure that there is record when field1 = 1 . 我确定在field1 = 1时有记录。 If I use $q->toSQL() the final SQL is: 如果我使用$q->toSQL()则最终的SQL是:

select * from (select * from table1 where field1 = ?) AS rs

When I paste this sql to phpmyadmin it returns 1 record. 当我将此sql粘贴到phpmyadmin时,它返回1条记录。 So it seems that Query builder causes this problem. 因此,似乎查询生成器会导致此问题。

Found it myself! 自己找到了! I should use: 我应该使用:

$q1 = Table1Model()::select()->where('field1', 1);

$q2 = \DB::table(\DB::raw('('.
    $q1->toSQL()
.') AS rs'))
->mergeBindings($q1->getQuery());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM