【问题标题】:Laravel How to get multi different results by executing only one queryLaravel 如何通过只执行一个查询来获得多个不同的结果
【发布时间】:2020-11-12 16:07:08
【问题描述】:

Laravel 版本:7.0

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

Above 返回所有已批准的帖子。

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

以上将获得 4 个按特色排序的帖子。

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

以上将获得 4 个由 created_at 订购的帖子。 ...

我怎样才能只用一个查询得到它们?

我想得到如下结果来使用它们。

$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]  

谁能帮助我?谢谢

【问题讨论】:

    标签: php laravel eloquent laravel-query-builder laravel-collection


    【解决方案1】:

    你需要试试这个:

    $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 Database: Query Builder

    【讨论】:

    • Method Illuminate\Database\Eloquent\Collection::orderBy does not exist.
    • 如果 orderBy 在您的 larave 中不起作用,请尝试 sortBy laravel.com/docs/5.7/collections#method-sortby 如果您仍然收到错误发布控制器代码
    • @THCBin 看着我的评论。
    猜你喜欢
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    相关资源
    最近更新 更多