将subselect sql查询转换为laravel查询

vuktfyat  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(343)

我有一个 mysql 在下面查询

select * from
  ( SELECT *,(select count(*) from `comments` where parent_id=b._id) as 
  cnt FROM `comments` b )x 
  where ((x.type_user='xxxx' and (cnt>0 or x.is_starter=1)) 
  or(type_user='user' and cnt>=0)) 
  and deleted_at is null and parent_id is null  order by created_at desc

我想把它转换成laravel查询

$res=DB::table('comments')
        ->select(DB::raw('comments.*, (select count(*) from `comments` b where b.parent_id=comments._id) as cnt'));

        $res->where(function ($query) {
            $query->where('comments.type_user','xxxx')
            ->where(function ($query1) {
                $query1->where('cnt','>',0)
                ->orWhere('comments.is_starter',1);
            });
        })->orWhere(function($query) {
            $query
            ->where('comments.type_user','user')
            ->where('cnt', '>=',0); 
        });

导致以下错误
sqlstate[42s22]:找不到列:“where子句”中的1054未知列“cnt”
请帮忙。提前谢谢

wvt8vs2t

wvt8vs2t1#

拉威尔5.6:

$res = DB::query()
    ->fromSub(function($query) {
        $query->select('*', DB::raw('(select count(*) from `comments` where parent_id=b._id) as cnt'))
            ->from('comments as b');
    }, 'x');

拉威尔<5.6:

$res = DB::query()
    ->from(DB::raw('(SELECT *, (select count(*) from `comments` where parent_id=b._id) as cnt FROM `comments` b) x'));

相关问题