Yii2: asArray() with select undefined id

Created on 6 Sep 2017  ·  10Comments  ·  Source: yiisoft/yii2

What steps will reproduce the problem?

->select(['country_id'])
                ->groupBy(['country_id'])
                ->asArray()
                ->all();

executing this code have been producing an error undefined index: id;
vendoryiisoftyii2\db\ActiveRelationTrait.php line 458

What is the expected result?

array of array of ids
but

->select(['country_id'])
                ->groupBy(['country_id'])
                ->asArray()
                ->column();

it is working!

What do you get instead?

executing this code have been producing an error undefined index: id;
vendoryiisoftyii2\db\ActiveRelationTrait.php line 458

Additional info

| Q | A
| ---------------- | ---
| Yii version | 2.0.12
| PHP version | 5.6
| Operating system | windows-7

full query

 $countries_id = Moments::find()->joinWith(['addresses',], true, 'inner join')
                ->where([MomentAddresses::tableName() . '.status' => 0])
                ->select(['country_id'])
                ->groupBy(['country_id'])
                ->asArray()
                ->all();

as i tested the problem is asArray() is not working with select()

question

Most helpful comment

Does it work if you also select the id column?
If you don't need the relational data in the result you can turn eager loading off.

//...
$countries_id = Moments::find()->joinWith(['addresses',], false, 'inner join')
//...

All 10 comments

Does it work if you also select the id column?
If you don't need the relational data in the result you can turn eager loading off.

//...
$countries_id = Moments::find()->joinWith(['addresses',], false, 'inner join')
//...

Thank you for your question.
In order for this issue tracker to be effective, it should only contain bug reports and feature requests.

We advise you to use our community driven resources:

If you are confident that there is a bug in the framework, feel free to provide information on how to reproduce it. This issue will be closed for now.

_This is an automated comment, triggered by adding the label question._

It happens because when you do all() for AR query it returns ARs which need a primary key you're not selecting.

It happens because when you do all() for AR query it returns ARs which need a primary key you're not selecting.

ok! maybe this is crazy question but why it is working without asArray()?

Alex-Code i solved my problem with ->column() but i want to know the reason!
i use Yii2 more offen and i want to contribute to yii2 also but i think at the moment my knowledge is not enough to do this!

Because when using asArray() you get relations data so you need keys.

может я не понял вас, как я понял вас с asArray() запрос должен работать?
без использования метода ->asArray() запрос работает с методом ->all(), он создает AR
спс за ваш внимание и ответ!

Поправил комментарий, ошибся в нём. asArray() заставляет вытянуть relation-ы сразу, а им требуются ключи.

В свое время необходимо было очищать eager подгрузку из запроса. $this->with = null не помог, поскольку еще в ключах join есть указатель подгружать ли данные связей. Написал простой метод для ActiveQuery, который помог:

public function resetWith()
    {
        $this->with = [];

        if($this->joinWith){
            foreach($this->joinWith AS &$join){
                $join[1] = false;
            }

            unset($join);
        }

        return $this;
    }

Также метод, позволяющий просмотреть весь запрос, который будет выполнен:

public function getRawSql()
    {
        $builder = Yii::$app->db->queryBuilder;

        $query = clone $this;
        $query->resetWith();

        return $query->prepare($builder)->createCommand()->rawSql;
    }

Главная особенность в том, чтобы очищать eager подгрузку, иначе будут те же ошибки с ключами

Was this page helpful?
0 / 5 - 0 ratings