Yii2 Select only few columns from related model

Ljudotina picture Ljudotina · Oct 13, 2015 · Viewed 19.5k times · Source

In controller i have:

public function actionGetItems()
{
    $model = new \app\models\WarehouseItems;
    $items = $model->find()->with(['user'])->asArray()->all();
    return $items;
}

In WarehouseItem model i have standard (created by gii) relation declaration:

public function getUser()
{
    return $this->hasOne('\dektrium\user\models\User', ['user_id' => 'user_id']);
}

How can i control which column data do i get from "user" relation? I currently get all columns which is not good as that data is being sent to Angular in JSON format. Right now i have to loop trough $items and filer out all columns i dont want to send.

Answer

soju picture soju · Oct 13, 2015

You should simply modify the relation query like this :

$items = \app\models\WarehouseItems::find()->with([
    'user' => function ($query) {
        $query->select('id, col1, col2');
    }
])->asArray()->all();

Read more : http://www.yiiframework.com/doc-2.0/yii-db-activequerytrait.html#with()-detail