Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 774
Ljudotina Avatar asked Oct 13 '15 15:10

Ljudotina


2 Answers

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

like image 77
soju Avatar answered Oct 27 '22 21:10

soju


Your code should go this way.

public function actionGetItems()
{
    $items = \app\models\WarehouseItems::find()
        ->joinWith([
             /*
              *You need to use alias and then must select index key from parent table
              *and foreign key from child table else your query will give an error as
              *undefined index **relation_key**
              */
            'user as u' => function($query){
                $query->select(['u.user_id', 'u.col1', 'u.col2']);
            }
        ])
        ->asArray()
        ->all();

    return $items;
}
like image 43
Ankit Singh Avatar answered Oct 27 '22 22:10

Ankit Singh