what does indexBy() do ?

I was viewing sample code yii2-shop by samdark and saw indexBy(). I did some google search and still dont understand what IndexBy() do ?


$categories = Category::find()->indexBy('id')->orderBy('id')->all();

Would anyone please explain what indexBy(‘id’) do in the above code ? and why you would use it ?

Instead of returning an array indexed by integers, starting at zero and going up…

[0] -> whatever

[1] -> whatever

This will return an array indexed by the ‘id’ field. Or, you can pass it an anon function and have it return other data from the row like username, etc.

See this…

http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#indexing-query-results

thanks, it now makes sense :)