【问题标题】:Laravel: collect() helper - set type of collectionLaravel:collect() 助手 - 设置集合类型
【发布时间】:2019-04-24 23:38:20
【问题描述】:

如果我这样做:

$obj = factory(Object::class)->make();

collect($obj);

我返回了一个类型的集合:

Illuminate\Support\Collection

Laravel 还允许您使用特定方法定义自己的集合。在模型中,您可以:

public function newCollection(array $models = [])
{
    return new CustomCollection($models);
}

你会在文件 CustomCollection.php 中创建你的CustomCollection,像这样开始:

class CustomCollection extends Collection
{

我想知道如何返回一个类型的集合:

Illuminate\Database\Eloquent\Collection

或者,在创建我自己的自定义集合的情况下,我如何返回一个类型的集合:

App\Models\CustomCollection

我想使用 collect() 帮助程序或任何其他我不访问数据库以编写 PHPUnit 测试的方式来执行此操作。

===========

编辑:我正在使用 factory(Object::class)->make() 来欺骗 Eloquent 对象,我试图将这些对象放入集合中。

如果您只使用 factory(Object::class, 1)->make(),工厂会为您将 Object::class 的单个实例滚动到 Eloquent 集合中。

【问题讨论】:

    标签: laravel phpunit laravel-collection


    【解决方案1】:

    collect() 助手只是创建了一个新的Illuminate\Support\Collection 实例。

    function collect($value = null)
    {
        return new Collection($value);
    }
    

    你可以对任何集合做同样的事情。

    Illuminate\Database\Eloquent\Collection

    $collection = new Illuminate\Database\Eloquent\Collection($value);
    

    App\Models\CustomCollection

    $collection = new \App\Models\CustomCollection($value);
    

    【讨论】:

      【解决方案2】:

      由于您正在使用:

      $obj = factory(Object::class)->make();
      

      欺骗 Eloquent 对象,如果你只是这样做:

      $collection = factory(Object::class, 1)->make()
      

      factory() 为您将 Object::class 的单个实例滚动到 Eloquent 集合中。 1 是生成的集合中的对象数,因此如果您想要 2 个对象等,可以将其更改为 2

      【讨论】:

        猜你喜欢
        • 2020-02-10
        • 2021-05-19
        • 1970-01-01
        • 1970-01-01
        • 2019-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多