2016-05-16 41 views
1

我送與$ HTPP後的數組等等,雖然:如何處理yii2寧靜服務中的發佈數據?

var results = services.transaction('orderdetails/insert', 
         {customer_id: $scope.order.customer_id, data: $scope.orderDetail}); 

其中$ scope.orderdetail是ui_grid檢索到的一組數據:

  $scope.orderDetail = []; 

      for (var i = 0; i < gridLength; i++) { 
       $scope.orderDetail.push({ 
       "product_id": $scope.grid[i].product.id, 
       "quantity": $scope.grid[i].quantity, 
       "custom_price": $scope.grid[i].price 
      }); 

     } 

,並在我的actionInsert處理它( ):

public function actionInsert() { 
    $request = Yii::$app->request; 
    $customer_id = $request->getBodyParam('customer_id'); 
    $data = $request->getBodyParam('data'); 
} 

的問題是,數組$數據沒有鑰匙,當我試圖通過 它遍歷在我actionInsert。但是當我回到它,我得到這個數據作爲響應,在告訴它的數組:

data:Array[2] 
0: Object 
custom_price: 5000 
product_id: 4 
quantity: 6 
1: Object 
custom_price: 8000 
product_id: 2 
quantity: 8 

我的目標是使用事務插入這些數據,按照下列步驟:

1-插入表中的CUSTOMER_ID訂購

2獲得最後訂單ID將其插入ORDERDETAILS

3-插入的其他值的數組,但我想在每次插入添加順序編號。

我做了這樣的:

$sql1 = "insert into `order`(customer_id) values($customer_id);"; 
    $sql2 = 'select @orderNumber := max(id) from `order`;'; 

//**Transaction**// 
    $connection = Yii::$app->db; 
    $transaction = $connection->beginTransaction(); 
    try { 
     $connection->createCommand($sql1)->execute(); 
     $connection->createCommand($sql2)->execute(); 

      $connection->createCommand("INSERT INTO `orderdetails` (oder_id, product_id, quantity, custom_price) " 
        . "VALUES (@orderNumber, $values")->execute(); 


     $transaction->commit(); 
    } catch (Exception $e) { // an exception is raised if a query fails 
     $transaction->rollback(); 
    } 
    //**end transaction 

我知道我不得不使用這樣的事情:

foreach(array_keys($data) as $key) { 

     $fields[] = "`$key`"; 
     $values[] = "'" . \Yii::$app->db->quoteValue($data[$key]) . "'"; 

} 
$fields = implode(",", $fields); 
$values = implode(",", $values); 

但正如我之前提到的,我的$的數據有意外鍵0,1等等,但我需要custom_price和其他。爲什麼數組不符合預期以及如何使@orderNumber的插入語句附加到每個數組對象的第一個元素。

謝謝;

回答

1

解決:

$sql1 = "insert into `order`(customer_id) values($customer_id);"; 
    //**Transaction**// 
    $connection = Yii::$app->db; 
    $transaction = $connection->beginTransaction(); 
    try { 
     $connection->createCommand($sql1)->execute(); 

     $orderNumber = Yii::$app->db->getLastInsertID(); 
     foreach ($data as $value) { 
      $model = new Orderdetails; 
      $model->order_id = $orderNumber; 
      $model->attributes = $value; 
      if (!$model->save()) { 
       throw new Exception('Insertion failed'); 
      } 
     } 
     //.... other SQL executions 
     $transaction->commit(); 
    } catch (Exception $e) { // an exception is raised if a query fails 
     $transaction->rollback(); 
    } 
    //**end transaction