【问题标题】:Laravel collection paginate with where clauseLaravel 集合用 where 子句分页
【发布时间】:2020-06-02 17:38:39
【问题描述】:

我有一个新闻表,我管理已读或未读标志。所以我想分页两个标志是分开的,而不需要额外的数据库查询。 我的要求是获取所有新闻并过滤已读或未读并为单独的表格视图分页。 一旦我尝试以下代码但收到错误Method Illuminate\Database\Eloquent\Collection::paginate does not exist.

    $ns=News::all();
    $ns->where('read',1)->paginate(2);
    $ns->where('read',0)->paginate(2);

我想只使用一个数据库查询来做到这一点。

【问题讨论】:

  • 你的方法不对。试试这个$ns = News::where('read', 1)->paginate(2);
  • 试试下面的代码 $readns = News::where('read',1)->paginate(2); $unreadns = News::where('read',0)->paginate(2);
  • @TalhaF。没有分页功能,查询是正确的。我想知道,如何使用 where 子句对集合进行分页。
  • 既然你有一个集合,你可以使用切片。 $ns->where('read',1)->splice($index, $howMany);在那里,您必须管理某种计数器来查看所有记录,但这是一个想法。

标签: laravel eloquent laravel-6


【解决方案1】:

你可以试试下面的代码

$readns = News::where('read',1)->paginate(2);
$unreadns = News::where('read',0)->paginate(2);

你可以使用 chunk() 。检查这个laravel.com/docs/7.x/queries#chunking-results

【讨论】:

【解决方案2】:

Laravel paginate 无法从集合中进行分页,您需要 eloquent 查询构建器。

https://laravel.com/docs/7.x/pagination#paginating-query-builder-results

所以,如果您仍然想从集合中进行分页,您可以使用宏为集合创建自定义分页。这个要点中有一个例子:

https://gist.github.com/simonhamp/549e8821946e2c40a617c85d2cf5af5e

【讨论】:

    【解决方案3】:

    请尝试将其添加到助手中

    function paginate($items, $perPage = 15, $page = null, $options = []) {
        $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
        $items = $items instanceof Collection ? $items : Collection::make($items);
        return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
    });
    

    用法:

    $ns = News::all();
    $ns1 = paginate((clone $ns)->where('read', 1), 2);
    $ns2 = paginate((clone $ns)->where('read', 0), 2);
    

    【讨论】:

    • 方法 Illuminate\Database\Eloquent\Collection::paginate 不存在。
    猜你喜欢
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 2019-04-14
    相关资源
    最近更新 更多