简体   繁体   中英

get data related with yii2 on controller

I have data like this :

Table feedback , with entity : id_feedback (primary_key) , id_user (foreign key), feedback .
Table user , with entity : id_user (primary_key), user_name .

User has many feedback, feedback has one user.

I create json in app/controller/feedback .

public function actionGetReplayFeedback($ID_KOMENTAR)
{
    $replay = Feedback::find()->where('REPLAY_TO_ID = '. $ID_KOMENTAR)->all();
    echo Json::encode($replay);
}

I get the json but i didn't get the username . How can I get the username ?

You should simply try :

public function actionGetReplayFeedback($ID_KOMENTAR)
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    return Feedback::find()->with(['user'])->where(['REPLAY_TO_ID'=>$ID_KOMENTAR])->asArray()->all();
}

Read more :

soju is right and if you want to select only some columns (so not all columns of the models feedback and user is returned) you modify the select to something like this

$items = \app\models\Feedback::find()
->with(['user' => function($q) {
    $q->select(['id_user', 'username']);
}])
->select(['id_feedback', 'feedback'])
->where(['REPLAY_TO_ID'=>$ID_KOMENTAR])
->asArray()
->all();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM