簡體   English   中英

Laravel 如何通過只執行一個查詢來獲得多個不同的結果

[英]Laravel How to get multi different results by executing only one query

Laravel版本:7.0

$posts = Post::where("status", 1)->get();

以上返回所有已批准的帖子。

$top_featured_posts = Post::where("status", 1)->orderBy("featured", "DESC")->take(4);

以上將按特色獲得 4 個帖子順序。

$top_recent_posts = Post::where("status", 1)->latest()->take(4);

以上將通過 created_at 獲得 4 個帖子訂單。 ...

我怎樣才能只用一個查詢來獲得它們?

我想得到如下結果來使用它們。

$top_featured_posts[0], $top_featured_posts[1], $top_featured_posts[2], $top_featured_posts[3]  

$top_recent_posts[0], $top_recent_posts[1], $top_recent_posts[2], $top_recent_posts[3]  

誰能幫我? 謝謝

你需要試試這個:

$posts = Post::where("status", 1)->get();

$top_featured_posts = $posts->sortByDesc("featured", "DESC")->take(4)->values();

$top_recent_posts = $posts->sortByDesc("created_at")->take(4)->values();

文檔Laravel 數據庫:查詢生成器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM