A
A
acid23m2015-10-08 18:42:05
Yii
acid23m, 2015-10-08 18:42:05

How to select only required columns in YII2 when eager loading?

The documentation says that you can manage a query when eager loading with an anonymous function:
When eagerly loading a relation, you can customize...
And an example is given:

$customers = Customer::find()->with([
    'country',
    'orders' => function ($query) {
        $query->andWhere(['status' => Order::STATUS_ACTIVE]);
    },
])->all();

In this example, all columns are taken from the `order` table , but I don't need them all. By analogy, I should do this:
...
'orders' => function ($query) {
    $query->addSelect(['id', 'title', 'date']);
    $query->andWhere(['status' => Order::STATUS_ACTIVE]);
},
...

But it doesn't work, nothing is returned at all, an empty array.
What's wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
LittleFatNinja, 2015-10-08
@LittleFatNinja

see what ready request is being formed

A
acid23m, 2015-10-08
@acid23m

Here is my request:

$data = AddressClassificator::find()
            ->select('id, iata')
            ->with(['addressClassificatorTranslates' => function($query) {
                $query->addSelect(['id', 'name', 'country', 'city']);
                $query->andWhere(['lang' => Yii::$app->language]);
            }])
            ->asArray()
            ->all();

Generated SQL
at the exit
[
    0 => [
        'id' => '1'
        'iata' => 'AAA'
        'addressClassificatorTranslates' => []
    ]
]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question