2014-12-02 119 views
0

我正在建设一些新闻网站,我想知道一个类别中有多少个子类别。我建立这个查询。 (它工作在我的数据库)现在我想我把它转换成laravel查询生成器,但我无法得到它的工作。查询到laravel查询生成器

原始查询:

SELECT news_categories.id, 
      news_categories.name, 
      news_categories.description, 
      count(nc.id) 
    FROM happyalphen.news_categories 
LEFT JOIN news_categories nc ON nc.category_parent = news_categories.id 
    WHERE news_categories.category_parent = 0 
GROUP BY news_categories.id ; 

我现在有

DB::table('news_categories') 
    ->selectRaw('news_categories.id') 
    ->join('news_categories subCat', 'news_categories.category_parent', '=', 'subCat.id') 
    ->where('news_categories.category_parent','=',0) 
    ->groupBy('news_categories.id') 
    ->get(); 

表布局

table layout

+0

告诉我们,为什么你不能得到它的工作,否则没有人会关心帮助您prbably。在这种情况下:无需'selectRaw',简单'select'会做,并添加'as'别名表'join('news_categories as subCat'..' – 2014-12-02 13:52:53

+0

你好像是左连接'news_categories'到自己,还是来自服务器上的另一个数据库? – msturdy 2014-12-02 14:13:59

回答

0

我发现它了(谢谢Jarek Tkacyk)

我忘记了laravel停止查询中的'AS'。

DB::table('news_categories') 
    ->selectRaw(' `news_categories`.`id`, `news_categories`.`name`, `news_categories`.`description`, `news_categories`.`color`, `news_categories`.`text_color`, count(`SubCat`.`id`) as SubCatCount ') 
    ->join('news_categories as subCat', 'subCat.category_parent', '=', 'news_categories.id','left') 
    ->where('news_categories.category_parent','=','0') 
    ->groupBy('news_categories.id') 
    ->get();