代码之家  ›  专栏  ›  技术社区  ›  Phiter

Laravel集合中的“跳过”方法

  •  2
  • Phiter  · 技术社区  · 7 年前

    在查询生成器中( \Illuminate\Database\Query\Builder ),可以同时使用 skip($n) take($n) 方法。

    在集合中( \Illuminate\Support\Collection ),可以使用 take($n) 函数,但没有 跳过(n美元) 作用

    为什么会这样?还有其他选择吗?

    2 回复  |  直到 7 年前
        1
  •  3
  •   Community CDub    5 年前

    这个 skip($n) 方法确实不包括在 Collection 类,但有一个函数执行相同的操作: slice($n) .

    QueryBuilder(摘自文档):

    $users = DB::table('users')->skip(10)->take(5)->get();
    

    或者,您可以使用限制和偏移方法:

    $users = DB::table('users')
                    ->offset(10)
                    ->limit(5)
                    ->get();
    

    集合:

    collect([1, 2, 3, 4])->slice(2)->all(); //[3, 4]
    

    中的许多方法 QueryBuilder 类在中不可用 收集 类,反之亦然。但它们都有类似的功能,比如 QueryBuilder where 函数,您可以使用 filter 功能以实现类似的结果。

        2
  •  0
  •   apokryfos    6 年前

    forPage方法返回一个新集合,其中包含将出现在给定页码上的项。该方法接受页码作为其第一个参数,并接受每页显示的项数作为其第二个参数:

    $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
    
    $chunk = $collection->forPage(2, 3);
    
    $chunk->all();