问题
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 sortBy
method 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