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

从转换内部的分页中删除行

  •  1
  • Goose  · 技术社区  · 6 年前

    我有一个变量是分页对象

    $pagination
    

    我在用变换改变里面的东西

    $pagination->getCollection()->transform(function ($item, $key) use(&$data, &$pagination) {
        $item->foo = 'bar';
    }
    

    $pagination->getCollection()->transform(function ($item, $key) use(&$data, &$pagination) {
        $data[] = $item->foo;
        if ($item->foo === 'bar') {
            $item->remove();
        }
    }
    

    我也试过用 $pagination->getCollection()->forget($key); 变换内部

    $pagination->getCollection()->transform(function ($item, $key) use(&$data, &$pagination) {
        $data[] = $item->foo;
        if ($item->foo === 'bar') {
            $pagination->getCollection()->forget($key);
        }
    }
    

    这是这个问题的答案。

    How to unset (remove) a collection element after fetching it?

    我想我正在处理的一个分页的事实可能是使这些答案不适用于我的情况。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Goose    6 年前

    单独收集分页 filter() 允许基于复杂条件从分页中删除项。我在转换中返回false,然后在过滤器中简单地将其作为目标。

    $pagination = $pagination->getCollection()->filter(function ($item) {
        return $item;
    });
    

    编辑:

    // Remove already merged rows
    $itemsTransformed = $pagination->getCollection()->filter(function ($item) {
      return $item;
    });
    
    // Recreate because filter removed pagination properties
    $itemsTransformedAndPaginated = new \Illuminate\Pagination\LengthAwarePaginator(
      $itemsTransformed,
      $pagination->total(),
      $pagination->perPage(),
      $pagination->currentPage(), [
        'path' => \Request::url(),
        'query' => [
          'page' => $pagination->currentPage()
        ]
      ]
    );