Questionnaire.php
3.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php
namespace app\mobile\controller;
use app\common\controller\Api;
use app\mobile\model\QuestionnaireQuestion;
use app\mobile\model\QuestionnaireAnswer;
use think\Db;
use think\Exception;
use think\exception\PDOException;
/**
* 问卷接口
* @ApiWeigh (98)
*/
class Questionnaire extends Api
{
protected $noNeedLogin = ['questionList'];
protected $noNeedRight = ['*'];
public function _initialize()
{
parent::_initialize();
}
/**
* @ApiTitle (问卷-题目列表)
* @ApiSummary (问卷-题目列表)
* @ApiMethod (POST)
* @ApiReturn({
"code": 1,
"msg": "成功",
"time": "1599032660",
"data": {
"list": [{ //题目列表
"id": 1, //题目ID
"title": "测定混凝土立方体抗压强度时,标准试件的尺寸是( )㎜。", //题目
"option": [{ //题目选项
"key": "A", //选项
"value": "1" //选项内容
}],
"type": "1", //题目类型:1=单选题,2=多选题,3=判断题,4=简答题
}]
}
})
*/
public function questionList()
{
$list = QuestionnaireQuestion::field('id,title,option,type')->select();
foreach ($list as $v){
$v->option = json_decode($v['option'],true);
}
$this->success('成功',compact('list'));
}
/**
* @ApiTitle (问卷-提交)
* @ApiSummary (问卷-提交)
* @ApiMethod (POST)
*
* @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
*
* @ApiParams (name="content", type="string", required=true, description="[{id: 问题ID,value: 回答选项或内容}]")
*
* @ApiReturn({
"code": 1,
"msg": "成功",
"time": "1599032660",
"data": null
})
*/
public function submit()
{
$content = $this->request->post('content');
empty($content) && $this->error('缺少必要参数');
if(is_string($content)){
$content = htmlspecialchars_decode($content);
}
$answer_list = json_decode($content,true);
$no_answer = QuestionnaireQuestion::where('id','not in', array_column($answer_list,'id'))->field('id')->find();
!empty($no_answer) && $this->error('请回答第'.$no_answer['id'].'题');
foreach ($answer_list as $v){
empty($v['value']) && $this->error('请回答第'.$v['id'].'题');
}
Db::startTrans();
try{
$result_id = db('mobile_questionnaire_result')->insertGetId([
'user_id' => $this->auth->id,
'createtime' => time(),
'updatetime' => time()
]);
$insertAll = [];
foreach($answer_list as $val){
$insertAll[] = [
'user_id' => $this->auth->id,
'result_id' => $result_id,
'question_id' => $val['id'],
'content' => $val['value'],
];
}
(new QuestionnaireAnswer)->saveAll($insertAll);
Db::commit();
}catch (PDOException $e){
Db::rollback();
$this->error($e->getMessage());
}catch (Exception $e){
Db::rollback();
$this->error($e->getMessage());
}
$this->success('提交成功');
}
}