[英]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 ,我正在使用 Yii2 框架构建简单的 API,我的数据库包含问题表,该表包含 (question_type) 列和该列的值(1 或 2),我在 Question 模型中创建了一个函数来获取每个问题的类型..我创建 api 以从表中检索所有问题,但是当调用该函数时显示此错误
Trying to get property 'id' of non-object
,如何解决此问题,
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.方法
all()
返回 ActiveRecord 对象数组。 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.当然,如果你想得到一个对象而不是一组对象,你可以使用one()函数。 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'];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.