Yii2 Select only a few columns from the corresponding model

In the controller, I have:

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

In the WarehouseItem model, I have a standard (created by gii) relation expression:

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

How can I control what column data I can get from the user relationship? Currently, I get all the columns that are not very good, as this data is sent to Angular in JSON format. Right now I have a loop through $ items and filer from all the columns that I don't want to send.

+8
yii2 yii2-model
source share
2 answers

You should simply modify the relationship request as follows:

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

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

+12
source share

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; } 
0
source share

All Articles