php - 查询 Laravel 查询生成器

标签 php mysql laravel laravel-4

我正在建立一个新闻网站,我想知道一个类别中有多少个子类别。我构建了这个查询。 (它适用于我的数据库)现在我想将其转换为 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

最佳答案

我找到了(感谢 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/

相关文章:

php - MySQL Select 与动态 where 子句不同

php - Jquery DataTables 可排序距离列

mysql - 存储数据关系的更好方法(Redis 或 Mysql)

laravel - 如何比较两个碳时间戳?

laravel - 如何为 Laravel 更新密码表单编写测试?

php - [0] 处的所有数组值键都带有简单的 html dom

javascript - 使用多个文本框执行数据库搜索

mysql - 结构 : SQL table fields with sub options

MYSQL - 插入一个空值,如何避免?

php - 未定义表 : 7 ERROR: relation "expenses" does not exist