将subselect sql查询转换为laravel查询

时间:2018-05-30 13:28:21

标签: mysql laravel

我在

下面有一个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 query.this是我尝试

  $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]:未找到列:1054'where'中的未知列'cnt'   条款“

请提前帮助。谢谢

1 个答案:

答案 0 :(得分:1)

Laravel 5.6:

NUM   status  name
 1       +       A
 4       -       A    
 2       +       A
 5       -       A 
 8       +       A   
 10      -       A 
 3       +       B 
 9       -       B
 6       +       C 
 7       -       C 

Laravel< 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');