【问题标题】:query to laravel query builder查询到 laravel 查询生成器
【发布时间】:2014-12-02 13:50:03
【问题描述】:

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

表格布局

【问题讨论】:

  • 告诉我们为什么你不能让它工作,否则没有人会愿意帮助你。在这种情况下:不需要selectRaw,简单的select就可以,并添加@ 987654326@ 到别名表join('news_categories as subCat' ..
  • 你似乎是左连接 news_categories 到它自己,还是来自服务器上的另一个数据库?

标签: php mysql laravel laravel-4


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 2019-01-29
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多