Search code examples
yii2yii2-model

Yii2 Select only few columns from related model


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.


Solution

  • 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