Yii2: ActiveRecord::find()->indexBy()->column() not indexing as expected

Created on 2 Mar 2015  路  14Comments  路  Source: yiisoft/yii2

Given the documentation of select(), indexBy and column() I expected

Book::find()->select('title')->indexBy('isbn')->column()

to return an associative array of book titles indexed by ISBN. It returned instead a numeric array of titles. The following produced the same result.

Book::find()->select(['title', 'isbn'])->indexBy('isbn')->column()

In other words, for the above two cases indexBy() doesn't do anything.

The following returned an array of Book models indexed by ISBN but if indexBy is only supposed to work with certain getters like all() then the documentation for indexBy() should say so.

Book::find()->indexBy('isbn')->all()

If indexBy() is really just an option for all() then shouldn't it be a parameter of that method rather than a property of Query.

ready for adoption enhancement

Most helpful comment

@MelleDijkstra try ->select('name')->indexBy('id')->column()

All 14 comments

That's more of design decision. @qiangxue is it expected or should be fixed?

This is currently working as expected as column() uses the native PDO column fetch mode.
But I think we can consider enhancing column() in this case.

We mainly need to modify yii\db\Query::column() so that when indexBy is set, it should fetch multiple columns. Things get tricky, though, when indexBy is a callable.

it worked before

@samdark what does "status:ready for adoption" mean?

Means that it is OK to improve it so it could be worked on.

I have same issue. @samdark @qiangxue when it will be adopted? This issue allows to save proccessing time and forget about ArrayHelper::map().

You can speed things up by working on a pull request.

It's really good news, if select(['id', 'name']), indexBy('id') and column('name') will return result:
array(id=>name)

column($db = null)

column fetch first column, i use it

MyModel::find()->select('name', 'id')->indexBy('id')->column()

Anyway it's more useful, than use ArrayHelper for this simple need.

Is there already an easier way instead of using ArrayHelper to get the following result:
~
[id => name]
~

All I'm getting is (->select(id,name)->indexBy(id)->all()):
~
[id => [id, name]]
~

@MelleDijkstra try ->select('name')->indexBy('id')->column()

@tom-- I'll give it a try!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

alexraputa picture alexraputa  路  53Comments

alexandernst picture alexandernst  路  163Comments

AstRonin picture AstRonin  路  49Comments

sapsxxxil picture sapsxxxil  路  50Comments

samdark picture samdark  路  63Comments