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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With