Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - get the top 5 by number of occurrences

I have tables comments, votes, views, likes which have article_id field. I am trying to get first 5 articles from those tables, by the number of occurrences in them. I am sending $modelName to my function and then trying to get results from the queries. This is how my query looks like now:

private function query($modelName) {
        $mostSomethingArticle = $modelName->all()->groupBy('article_id')->take(5);

        return $mostSomethingArticle;

      }

Right now, I am getting, this kind of result:

Collection {#398 ▼
  #items: array:5 [▼
    5 => Collection {#377 ▼
      #items: array:5 [▶]
    }
    2 => Collection {#376 ▼
      #items: array:1 [▶]
    }
    6 => Collection {#397 ▼
      #items: array:3 [▶]
    }
    1 => Collection {#396 ▼
      #items: array:1 [▶]
    }
    7 => Collection {#395 ▼
      #items: array:5 [▶]
    }
  ]
}

I am wondering how to make a query where I would get first 5 results with the number of occurrences in 'desc' order.

like image 517
Ludwig Avatar asked Nov 23 '25 10:11

Ludwig


1 Answers

I am posting my workaround if anyone will need it in the future, instead of passing a $modelName, I have decided to get the name of the table from $request and then do the query like this:

$result = DB::table($request['option'])
                ->select(DB::raw('article_id'), DB::raw('count(*) as count'))
                ->groupBy('article_id')
                ->orderBy('count', 'desc')
                ->take(5)
                ->get();
like image 151
Ludwig Avatar answered Nov 25 '25 23:11

Ludwig