我正在建立一个新闻网站,我想知道一个类别中有多少个子类别。我构建了这个查询。 (它适用于我的数据库)现在我想将其转换为 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();
表格布局
最佳答案
我找到了(感谢 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();
关于php - 查询 Laravel 查询生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27251060/