Laravel 的 collection,你需要避免踩坑
Laravel 中 collection 有两个类
Illuminate\Support\Collection
Illuminate\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();
就好了
之前也犯过类似的错误,归根结蒂,是没搞清楚当前要处理的对象究竟是哪个类型的集合。
Illuminate\Database\Eloquent\Collection 是 集合的子类,
也就是 ORM 的get()方法返回的对象
emmmm……