简体   繁体   中英

How to access each record when query retrieved all records Yii2

I'm using Yii2 Framework to build simple API , my DB contain questions table and this table contain (question_type) column and the value of this column (1 or 2) and i create a function in Question model to get type each question .. and i create api to retrieve all questions from the table but when call the function this error displayed Trying to get property 'id' of non-object ,, how to solve this problem ,

this is my code in controller

public function actionGetQuestions(){
    \Yii::$app->response->format = \yii\web\Response:: FORMAT_JSON;
    $attributes = \yii::$app->request->post();
    $questions = Questions::find()->all();
    if($questions){
        return array(
            'status' => true,
            'data' => ['id'=> $questions->id , 'question_content' => $questions->question_content , 'Question Type' => $questions->checkQuestionType($questions->id) ,
            'Question Required Or Not' => $questions->checkQuestionRequired($questions->id) ]
        );
    }else{
        return array('status'=>false,'data'=> 'No Student Found');
    }
}

Method all() returns array of ActiveRecord objects. You must work with the result set with help loop statements and other methods of working with arrays. For example:

foreach ($questions as $question) {
   $id = $question->id;
}

Of course, if you want to get one object instead of an array of objects you can use one() function. For example:

$question = Questions::find()->where(['id' => <id-value>])->one();
$id = $question->id;

You should build data to response and return it. For example:

public function actionGetQuestions()
{

    \Yii::$app->response->format = \yii\web\Response:: FORMAT_JSON;

    $attributes = \yii::$app->request->post();
    $questions = Questions::find()->all();

    if(!empty($questions)) {
        $data = [];
        foreach ($questions as $q) {
            $data[] = [
                'id'=> $q->id , 
                'question_content' => $q->question_content , 
                'Question Type' => $q->checkQuestionType($questions->id) , 
                'Question Required Or Not' => $q->checkQuestionRequired($questions->id)
           ];
       }

       return [
          'status' => true,
          'data' => $data
       ];
    } else {
       return ['status' => false,'data' => 'No Student Found'];
    }
}

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