将收到的JSON信息保存到数据库中

时间:2016-02-03 11:34:39

标签: php json yii2

我有一个角度的客户端,在YII2中向我的服务器端发送一个JSON,其中包含有关报价的所有信息。 这是服务器端收到的JSON。

{  
   "client1":{  
      "id":"1",
      "selectedItem":{  
         "id":2,
         "software":"TV",
         "price":14850,
         "configuration":1,
         "workflow":1.5
      },
      "quantity":1,
      "locations":22,
      "notes":"hello",
      "cost":13500,
      "labor":"1.63",
      "workflow":1.5,
      "custom":0,
      "learning":35,
      "price":13500,
      "configuration":1
   },
   "client2":{  
      "id":"2",
      "selectedItem":{  
         "id":5,
         "software":"DVD",
         "price":2500,
         "configuration":0.5,
         "workflow":1.5
      },
      "quantity":2,
      "locations":136,
      "notes":"its me",
      "cost":5000,
      "labor":0,
      "workflow":1.5,
      "custom":0,
      "$$hashKey":"object:5",
      "price":2500,
      "configuration":0.5
   },
   "live":"11",
   "training":"1",
   "staffTraining":"4"
}

需要在数据库中创建记录但不知道如何访问产品信息只能访问livetrainingstaffTraining个键。

这是我要插入记录的表格

Database Diagram

添加报价的服务器代码

public function actionCreate() {
    $model = new Quote();
    Yii::$app->response->format = Response::FORMAT_JSON;

    if ($data=Yii::$app->request->post() ) {
        $model->attributes = $data;
        if($model->save()) {
            echo(json_encode("success"));
        } else {
            echo json_encode($model->errors);
        }
    } 
}

1 个答案:

答案 0 :(得分:0)

你可以试试这个,

 public function actionCreate(){
    Yii::$app->response->format = Response::FORMAT_JSON;
    if ($data=Yii::$app->request->post()){
        $responseArray=json_decode($data,true);
        foreach ( $responseArray as  $response) {
            $model = new Quote();
            $model->attributes=$response;
            $model->save();
        }
    }
}