Laravel 的 collection,你需要避免踩坑
Laravel 中 collection 有两个类
Illuminate\Support\CollectionIlluminate\Database\Eloquent\Collection
如果你用 collect($array) 方法,和 new Illuminate\Support\Collection($array) 的效果是一样的。
我今天在使用 Illuminate\Database\Eloquent\Collection 就踩了这个坑:
$collection = new \Illuminate\Database\Eloquent\Collection(['item a', 'item b', 'item c']);
$collection = $collection->unique();
执行时候会报错
PHP Fatal error: Call to a member function getKey() on string in /Project/nginx/webbpm-dev.ssl.lol/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Collection.php on line 259
[Symfony\Component\Debug\Exception\FatalErrorException]
Call to a member function getKey() on string
这是因为 Illuminate\Database\Eloquent\Collection 通过调用自身的 getDictionary 方法,使用根据主键去重复的逻辑覆盖了 Illuminate\Support\Collection 的逻辑。
以上代码改成
$collection = collect(['item a', 'item b', 'item c']);
$collection = $collection->unique();
就好了
关于 LearnKu
推荐文章: