/** * @return \yii\db\ActiveQuery */ public function getPurchaseDtls() { return $this->hasMany(PurchaseDtl::className(), ['id_product' => 'id_product']); }
/** * @return \yii\db\ActiveQuery */ public function getPurchaseDtls() { return $this->hasMany(PurchaseDtl::className(), ['id_warehouse' => 'id_warehouse']); }
/** * * @param PurchaseHdr $model * @return array */ protected function savePurchase($model) { $post = Yii::$app->request->post(); $details = $model->purchaseDtls; $success = false; if ($model->load($post)) { $transaction = Yii::$app->db->beginTransaction(); try { $formName = (new PurchaseDtl())->formName(); $postDetails = empty($post[$formName]) ? [] : $post[$formName]; if ($postDetails === []) { throw new Exception('Detail tidak boleh kosong'); } $objs = []; foreach ($details as $detail) { $objs[$detail->id_purchase_dtl] = $detail; } if (empty($model->id_warehouse) && count($details)) { $model->id_warehouse = $details[0]->id_warehouse; } if ($model->save()) { $success = true; $id_hdr = $model->id_purchase; $id_whse = $model->id_warehouse; $details = []; foreach ($postDetails as $dataDetail) { $id_dtl = $dataDetail['id_purchase_dtl']; if (isset($objs[$id_dtl])) { $detail = $objs[$id_dtl]; unset($objs[$id_dtl]); } else { $detail = new PurchaseDtl(); } $detail->setAttributes($dataDetail); $detail->id_purchase = $id_hdr; $detail->id_warehouse = $id_whse; if (!$detail->save()) { $success = false; break; } $details[] = $detail; } if ($success && count($objs) > 0) { $success = PurchaseDtl::deleteAll(['id_purchase_dtl' => array_keys($objs)]); } } if ($success) { $transaction->commit(); } else { $transaction->rollBack(); } } catch (Exception $exc) { $success = false; $model->addError('', $exc->getMessage()); $transaction->rollBack(); } if (!$success) { $details = []; foreach ($postDetails as $value) { $detail = new PurchaseDtl(); $detail->setAttributes($value); $details[] = $detail; } } } return [$details, $success]; }