【问题标题】:How to convert mysql query to laravel query builder?如何将 mysql 查询转换为 laravel 查询生成器?
【发布时间】:2023-03-07 00:51:01
【问题描述】:

我有 2 个表格,在第一个 cmets 和文章 id 中,在第二个文章标题中,id ,文章类别。我想要一个拥有最多 cmets 的文章的标题。

SELECT comments.article_id, news.title, news.category_id,
    COUNT(comments.id) as counts 
  FROM comments 
  JOIN news ON news.id = comments.article_id 
  GROUP BY(article_id) 
  ORDER BY counts DESC 
  LIMIT 3

我试过这个:

  $articles = DB::table('comments')
        ->join('news', 'news.id', '=', ' comments.article_id')
        ->select(comments.article_id', 'news.title', ' news.category_id')
        ->count('comments.id')
        ->groupBy('article_id')
        ->orderBy(DB::raw('count(comments.id)', 'desc')
        ->limit(3)
        ->get();

但是有:

Call to a member function groupBy() on integer

【问题讨论】:

    标签: mysql sql laravel


    【解决方案1】:

    您正在使用“整理器”,这意味着 ->count('comments.id') 不再返回 QueryBuilder 的实例,而是返回常规类型 (integer)。

    由于 PHP 中的 integers 不是类,因此您尝试在非类上执行方法,导致显示此错误消息。

    您肯定认识其他终结者,例如 ->sum()->all()->get()、...

    只需删除您的->count('comments.id') 行即可:

    $articles = DB::table('comments')
      ->join('news', 'news.id', '=', ' comments.article_id')
      ->select('comments.article_id', 'news.title', ' news.category_id')
      ->groupBy('article_id')
      ->orderBy(DB::raw('count(comments.id)', 'desc')
      ->limit(3)
      ->get();
    

    【讨论】:

      【解决方案2】:
      DB::table('comments')
      ->join('news', 'news.id', '=', ' comments.article_id')
      ->selectRaw('comments.article_id', 'news.title', ' news.category_id', 'count(comments.id) as countsxyz')
      ->groupBy('article_id')
      ->orderBy(DB::raw('countsxyz'), 'desc')
      ->limit(3)
      ->get();
      

      试试这个,如果您仍然遇到任何问题,请告诉我。

      【讨论】:

      • "selectRaw() 必须是数组类型,字符串给定"再次错误
      猜你喜欢
      • 2015-12-13
      • 2019-03-09
      • 1970-01-01
      • 2017-12-09
      • 1970-01-01
      • 2017-12-29
      • 1970-01-01
      • 2021-08-07
      • 2016-08-10
      相关资源
      最近更新 更多