How to order data twice. But make the firts orderBy ineffective

喜你入骨 提交于 2019-12-07 23:33:04

问题


I'm trying to get last 100 posts from database and than order them by likecount or another property and output only 5 of them, that way I will discover most liked 5 posts or viewed, or reported out of last 100 posts. What I tried so far is like below:

$lastHundredPost = Post::orderBy('id', 'desc')->take(100);
$post = $lastHundredPost->orderBy('likecount', 'desc')->take(2)->get();

this does not disable first orderBy property.

Laravel 5.4


回答1:


If you want to get result from the first query, use collections:

$lastHundredPost = Post::orderBy('id', 'desc')->take(100)->get();
$post = $lastHundredPost->sortByDesc('likecount')->take(2);



回答2:


My first idea is to execute sql query and get 100 row, and then use sortBymethod of your collection.

$lastHundredPost = Post::orderBy('id', 'desc')->take(100)->get();

$lastHundredPost->sortBy('likecount')->take(2);

Another idea is to use orderByRaw:

$posts = Post::orderByRaw('likecount DESC, id DESC')->take(2)->get();


来源:https://stackoverflow.com/questions/48584669/how-to-order-data-twice-but-make-the-firts-orderby-ineffective

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!