我正在使用Yii2 Framework构建简单的API,我的数据库包含问题表,并且该表包含(question_type)列和该列的值(1或2),并且我在Question模型中创建了一个函数以获取每个类型问题..并且我创建了api以从表中检索所有问题,但是当调用该函数时,此错误显示Trying to get property 'id' of non-object
,如何解决此问题
这是我在控制器中的代码
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');
}
}
答案 0 :(得分:1)
方法all()
返回ActiveRecord对象的数组。您必须使用帮助循环语句和其他使用数组的方法来处理结果集。例如:
foreach ($questions as $question) {
$id = $question->id;
}
当然,如果要获取一个对象而不是对象数组,可以使用one()函数。例如:
$question = Questions::find()->where(['id' => <id-value>])->one();
$id = $question->id;
您应该构建数据以响应并返回它。例如:
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'];
}
}