/** * goodsIdList = [goodID => quantity] * @param int $orderID * @param array $goodsIdList */ public static function saveOrderItems($orderID, $goodsIdList) { foreach ($goodsIdList as $id => $quantity) { $orderItemModel = new OrderItems(); $orderItemModel->order_id = $orderID; $orderItemModel->goods_id = $id; $orderItemModel->multiplicity = $quantity; $orderItemModel->firm_id = Goods::findOne($id)->firm_id; $orderItemModel->save(); } }
/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = OrderItems::find(); $dataProvider = new ActiveDataProvider(['query' => $query]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere(['id' => $this->id, 'order_id' => $this->order_id, 'goods_id' => $this->goods_id, 'multiplicity' => $this->multiplicity, 'firm_id' => $this->firm_id]); return $dataProvider; }
/** * Ajax */ public function actionSubmittedOrdersByAjax() { if (Yii::$app->request->isAjax) { /* Yii::$app->request->post() = {goodsID : quantity} */ $goodsIdList = Yii::$app->request->post(); if (!empty($goodsIdList)) { $orderID = Orders::saveOrder($goodsIdList); OrderItems::saveOrderItems($orderID, $goodsIdList); $link = \Yii::$app->homeUrl . '/index.php?r=orders/view&id=' . $orderID; $data = array('status' => 'ok', 'link' => $link); echo \yii\helpers\Json::encode($data); } else { $data = array('status' => 'unok'); echo \yii\helpers\Json::encode($data); } } }
/** * @return \yii\db\ActiveQuery */ public function getOrderItems() { return $this->hasMany(OrderItems::className(), ['order_id' => 'id']); }