2

I have 2 tables and in first comments and article id, in second article title, id , category of article. I want has a title of article which has the most comments.

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

I tried this:

  $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();

But had:

Call to a member function groupBy() on integer

2 Answers 2

2

You are using a "finisher", which means ->count('comments.id') does not return an instance of QueryBuilder anymore but a regular type (integer).

As integers in PHP are not classes, you are trying to perform a method on an non-class, which led to display this error message.

You surely know others finishers like ->sum(), ->all(), ->get(), ...

Just remove your line ->count('comments.id') and you will be good to go:

$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();
Sign up to request clarification or add additional context in comments.

Comments

0
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();

try this and let me know if you still face any issue.

1 Comment

"selectRaw() must be of the type array, string given " again error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.