controllers
接收传入参数,创建模型类对象,调用新增方法,将接收到的参数作为参数传入。
public function actionUserActionRecord()
{
$datas = Yii::$app->request->post();
$uor = new UserOperationRecord();
$records=$uor->addRecord($datas);
if(!empty($records)){
return json_encode([
'status'=>true,
'msg'=>$records
]);
}else{
return json_encode([
'status'=>false
]);
}
}
models
首先获取记录条数,然后获取记录并将其转换为JSON格式的数组(如果是在AJAX中参数格式为JSON格式不需要转换,项目中为安卓请求需要转换),最后在循环中将所有记录保存。将存储成功的记录ID保存到数组中返回给客户端
public function addRecord($datas)
{
$num = $datas['recordCount'];
$records = array();
$operation_record = json_decode($datas['operation_record'],true);
//$operation_record = $datas['operation_record'];
for ($i = 0; $i < $num; $i++) {
$uor = new UserOperationRecord();
$data = $operation_record[$i];
$uor->app_id = $data['appId'];
$uor->record_id = $data['recordId'];
$uor->app_name = $data['appName'];
$uor->module_id = $data['moduleId'];
$uor->module_name = $data['moduleName'];
$uor->action = $data['action'];
if (isset($data['vin'])) {
$uor->vin = $data['vin'];
}
if (isset($data['e_uid'])) {
$uor->e_uid = $data['e_uid'];
}
$uor->operating_time = $data['operatingTime'];
if ($uor->save()) {
array_push($records, $uor->record_id);
}
}
return $records;
}
AJAX
注意:如果是以下方式请求,models中不需要json_decode方法进行转换。
$.ajax({
url:"http://localhost:8088/framework/web/index.php?r=VehicleTerminalApplication/interface/user-action-record",
type:"post",
data:{
"recordCount":7,
"operation_record":[
{"action":"update","appId":1,"appName":"VehicleAPP","moduleId":4,"moduleName":"version","operatingTime":"2018-10-12 06:55:17","recordId":1},
{"action":"update","appId":1,"appName":"VehicleAPP","moduleId":4,"moduleName":"version","operatingTime":"2018-10-12 06:58:12","recordId":2},
{"action":"update","appId":1,"appName":"VehicleAPP","moduleId":4,"moduleName":"version","operatingTime":"2018-10-12 06:58:16","recordId":3},
{"action":"update","appId":1,"appName":"VehicleAPP","moduleId":4,"moduleName":"version","operatingTime":"2018-10-12 06:58:35","recordId":4},
{"action":"update","appId":1,"appName":"VehicleAPP","moduleId":4,"moduleName":"version","operatingTime":"2018-10-12 06:58:36","recordId":5},
{"action":"update","appId":1,"appName":"VehicleAPP","moduleId":4,"moduleName":"version","operatingTime":"2018-10-12 06:58:36","recordId":6},
{"action":"update","appId":1,"appName":"VehicleAPP","moduleId":4,"moduleName":"version","operatingTime":"2018-10-12 07:18:06","recordId":7}
]
},
success: function (data){
}
});
响应结果
{"status":true,"msg":["1","2","3","4","5","6","7"]}