gpt4 book ai didi

laravel - 扩展 Laravel Eloquent\Collection 类

转载 作者:行者123 更新时间:2023-12-02 10:37:40 25 4
gpt4 key购买 nike

据我了解,可以使用以下方法在模型中覆盖默认的 Eloquent\Collection 类:

public function newCollection(array $models = array()) {

return new CustomCollection($models);
}

如果我使用典型的查询,例如:

Model::where('name', $name)->get();

这很棒,因此我可以向 eloquent 集合类添加方法,例如:

$records = Model::where('name', $name)->get();

$records->toTable();

但是,例如,如果我在模型上使用分页:

Model::where('name', $name)->paginate(25);

它返回 Illuminate\Support\Collection 类的实例,而不是 Illuminate\Database\Eloquent\Collection

有没有办法覆盖或扩展典型的Illuminate\Support\Collection

我正在尝试向返回的 Collection 添加一个 toTable() 方法。我宁愿不必用我自己的分页服务提供商替换分页服务提供商。

谢谢!!

最佳答案

您需要替换分页服务提供程序以及分页库中的其他几个类。听起来你知道如何做到这一点,但我们希望得到另一个答案,但由于我有代码,我会将其放在这里给你。

您需要替换这些类/方法的原因是因为 Illuminate 中的文件直接引用 Illuminate 命名空间中的类实例。

在config/app.php中

替换

'Illuminate\Pagination\PaginationServiceProvider',

'ExtendedPaginationServiceProvider',

在自动加载器能够找到的位置创建一个名为 ExtendedPaginationServiceProvider.php 的新文件,并将以下内容放入其中

<?php

use Illuminate\Support\ServiceProvider;

class ExtendedPaginationServiceProvider extends ServiceProvider
{
/**
* @inheritdoc
*/
public function register()
{
$this->app->bindShared('paginator', function($app)
{
$paginator = new ExtendedPaginationFactory($app['request'], $app['view'], $app['translator']);

$paginator->setViewName($app['config']['view.pagination']);

$app->refresh('request', $paginator, 'setRequest');

return $paginator;
});
}
}

在自动加载器能够找到的位置创建一个名为 ExtendedPaginationFactory.php 的新文件,并将以下内容放入其中

<?php

use Illuminate\Pagination\Factory;

class ExtendedPaginationFactory extends Factory
{
/**
* @inheritdoc
*/
public function make(array $items, $total, $perPage = null)
{
$paginator = new ExtendedPaginationPaginator($this, $items, $total, $perPage);

return $paginator->setupPaginationContext();
}
}

在自动加载器能够找到的位置创建一个名为 ExtendedPaginationPaginator.php 的新文件,并将以下内容放入其中

<?php

use Illuminate\Pagination\Paginator;

class ExtendedPaginationPaginator extends Paginator
{
/**
* Get a collection instance containing the items.
*
* @return ExtendedCollection
*/
public function getCollection()
{
return new ExtendedCollection($this->items);
}
}

您会注意到上面返回了 ExtendedCollection 的新实例。显然将其替换为您在问题中引用的 CustomCollection 类。

供其他人引用,ExtendCollection 类可能类似于以下内容

在自动加载器能够找到的位置创建一个名为 ExtendedCollection.php 的新文件,并将以下内容放入其中

<?php

use Illuminate\Support\Collection;

class ExtendedCollection extends Collection
{

}

此外,创建这些文件后,不要忘记在终端中运行以下命令

composer dump-autoload

关于laravel - 扩展 Laravel Eloquent\Collection 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27021539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com