【问题标题】:Combining two collections and paginating them组合两个集合并对它们进行分页
【发布时间】:2015-03-04 02:28:58
【问题描述】:

所以我在数据库中有广告。 广告有 3 种类型。精选,大胆和免费。 我想在页面中显示它们。首先根据选择的类别。 我想首先按添加日期显示所有特色,然后按添加日期显示所有粗体和免费项目。我想给它们分页。

我试过这个:

    $adsFeatured = Ads::where('category', '=', $category)->where('status', 'enabled')->where('type', 'featured')->get();
    $adsOther = Ads::where('category', '=', $category)->where('status', '=', 'enabled')->where('type', '=', 'free')->orWhere('type', '=', 'bold')->get();
    $adsOther->merge($adsFeatured);
    $adsFeatured->paginate(15);

当然,如果我使用 get(),它不能分页,但如果我不使用它,我就不能合并它们,我想合并它们,因为我希望它将它们按那个顺序排列。

感谢您的帮助,我希望我已经正确解释了一切。 :)

【问题讨论】:

    标签: laravel laravel-4 pagination


    【解决方案1】:

    您应该能够在一个查询中做到这一点。试试这个

    $ads = Ads::selectRaw('*, IF(type = "featured",1,0) AS is_featured')
              ->where('category', $category)
              ->where('status', 'enabled')
              ->orderBy('is_featured', 'desc')
              ->orderBy('created_at', 'desc')
              ->paginate(15);
    

    【讨论】:

    • 它似乎确实获得了所有应该在该类别中的广告,但我无法获得“$ad->id”或类似的东西。我如何访问这些字段?跨度>
    • 抱歉,您必须选择 * 以及其他字段。查看编辑后的答案
    • 非常感谢您的帮助! ^_^ 这正是我所需要的:)
    猜你喜欢
    • 2017-08-01
    • 2023-03-18
    • 1970-01-01
    • 2022-10-04
    • 2018-05-10
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 2023-03-07
    相关资源
    最近更新 更多