【问题标题】:Custom laravel collection lost pagination meta data自定义 laravel 集合丢失分页元数据
【发布时间】:2022-03-25 02:44:25
【问题描述】:

我为我的模型创建了一个自定义集合,以便为我的集合中的每个项目应用一个函数。

我的控制器对数据进行分页,但似乎自定义集合丢失了所有分页元数据:

class Product extends Model
{

    /**
     * Create a new Eloquent Collection instance.
     *
     * @param array $models
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function newCollection(array $models = [])
    {
        return new ProductCollection($models);
    }
}

class ProductCollection extends Collection
{
    public function applyPrice()
    {
        $productIds = $this->pluck('id')->toArray();

        $stockPrice = ...

        return $this->transform(function (Product $product) use ($productsStockPrice) {
            if (array_key_exists($product->id, $$stockPrice)) {
                $product->price = $productsStockPrice[$product->id]['price'] ?? null;
            }

            return $product;
        });
    }
}

public function index()
    {
        $user = auth()->user();

        $products = Product::orderBy("name")
            ->paginate()
            ->applyPrice($healthcenter);

        return HealthcenterProductResource::collection($products);
    }

结果:

{
  "data": [...]
}

有没有可能避免这个问题?

【问题讨论】:

  • LengthAwarePaginator 和 Collection 是两个不同的类。

标签: php laravel


【解决方案1】:

试试这样:

toQuery()允许通过管道paginate生成分页

$products = Product::orderBy("name")
            ->applyPrice($healthcenter)->get()->toQuery()->paginate();

【讨论】:

    【解决方案2】:

    我的错误是应用与paginate() 函数链接的applyPrice() 函数。

    我刚换了:

    $products = Product::orderBy("name")
                ->paginate()
                ->applyPrice($value);
    

    作者:

    $products = Product::orderBy("name")
                    ->paginate()
    $products->applyPrice($value)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-14
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多