【问题标题】:How can I skip n items from laravel eloquent collection?如何从 laravel eloquent 集合中跳过 n 个项目?
【发布时间】:2017-03-06 10:37:45
【问题描述】:

为什么这不起作用?

$myFriends =Friend::where('status',1)->pluck('user_id');
$users = User::Where('active',1)->WhereNotIn('id',$myFriends)->get();     
$users =$users->skip(2)->take(3);

它给出以下错误

BadMethodCallException in Macroable.php line 74:
Method Skip does not exist.

【问题讨论】:

  • Macroable.php 第 74 行是什么?

标签: php laravel-5 eloquent


【解决方案1】:

使用slice 方法代替skip

$users->slice(2)->take(3);

或者简而言之:

$users->slice(2, 3);

它会跳过前 2 条记录并返回接下来的 3 条记录。


关于@ikurcubic 的评论答案已更新。

【讨论】:

  • 这个调用可以简化为$users->slice(2,3); From docs:如果你想限制返回切片的大小,将所需的大小作为第二个参数传递给方法。
【解决方案2】:

你可以改用forPage收集方法。你只需要分别输入你想要的页码和项数。

https://laravel.com/docs/5.5/collections#method-forpage

$chunk = collect($users)->forPage(2, 3);

logger($chunk->all());

【讨论】:

  • 唯一的问题是它没有完全模仿雄辩的take和skip。在 eloquent skip(0) 中,返回第一页,但在使用 forpage(0,8) 时返回最后一页。
【解决方案3】:

一旦你调用“->get()”,它就不再是查询构建器实例,你可以在其中使用“->skip()”和“->take”,甚至其他查询,如“->where”等..

如果你愿意,你必须在调用“->get()”之前调用它,所以你应该这样调用:

$users = User::Where('active',1)->WhereNotIn('id',$myFriends)->skip(2)->get();   

$users = User::Where('active',1)->WhereNotIn('id',$myFriends)->skip(2)->take(3);   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 2015-02-28
    • 2015-05-29
    • 2017-04-23
    • 1970-01-01
    相关资源
    最近更新 更多