Bro*_*shi 44 php laravel eloquent
当我通过Laravel的Eloquent ORM执行查询时,我希望将行ID作为数组结果键,当我想根据ID检查某些内容(使用array_key_exists)或做一些查找时(如果我需要结果数组中的特定条目)
有什么办法我可以告诉Eloquent设置字段ID的密钥吗? 见图像http://oi60.tinypic.com/kc02a8.jpg
Bho*_*tta 111
你可以干脆做
Model::all()->keyBy('category_id');
Run Code Online (Sandbox Code Playgroud)
干杯:)
tre*_*mby 33
既然你有雄辩的集合(子类中的泛型Collection
类),您可以使用getDictionary
方法.$collection->getDictionary()
将为您提供一个由主键键入的Category对象数组.
如果您想要另一个Collection而不是本机PHP数组,则可以改为使用$collection->keyBy($property)
.看起来你的主键是category_id
,所以$collection->keyBy('category_id')
.您可以使用该方法来键入任何属性,包括您可能编写的任何get mutators.
虽然Eloquent 扩展getDictionary
是唯一的,但是所有Laravel 对象都可以使用.请参阅Laravel 4.2 API文档或Laravel 5.0 API文档.Collection
keyBy
Collection