嘲笑一个雄辩的集合

问题描述 投票:3回答:1

我想,在解释原因方面没有任何意义,可以创建一个模拟Eloquent Collection

我试过这个:

        $collection = new \Illuminate\Database\Eloquent\Collection(
            array(
                new User( array( "id" => 1 ) ),
                new User( array( "id" => 2 ) ),
                new User( array( "id" => 3 ) ),
                new User( array( "id" => 4 ) ),
                new User( array( "id" => 5 ) )
            )
        );

        $collection->get(); // Fails

但事实证明,这个集合没有像你通常那样的->get()方法,例如:

User::take( 2 )->get();

这最终是因为\ Illuminate \ Database \ Eloquent \ Collection只是一个命名空间并使用\ Illuminate \ Database \ Collection

任何想法如何模拟真正正常工作的Eloquent Collection?

php unit-testing laravel eloquent
1个回答
5
投票

我发现你可以采用你想要创建的模型类型并在其上调用newCollection

$collection = new \User();
$collection->newCollection(
    array(
        new User( array( "id" => 1 ) ),
        new User( array( "id" => 2 ) ),
        new User( array( "id" => 3 ) ),
        new User( array( "id" => 4 ) ),
        new User( array( "id" => 5 ) )
    )
);

http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_newCollection

© www.soinside.com 2019 - 2024. All rights reserved.