public function move($runValidation = true) { if ($runValidation && !$this->validate()) { return false; } return $this->_goods->moveSurplus($this->amount, '管理人员调整库存。'); }
public function actionSubtract() { $goodsId = (int) Yii::$app->request->post('goodsId'); $output = ['status' => 'fail', 'data' => []]; $goods = Goods::findOne(['id' => $goodsId, 'status' => Goods::STATUS_NORMAL]); if (!$goods) { return $output; } $model = CartGoods::findOne(['goods_id' => $goodsId, 'user_id' => Yii::$app->user->id]); if ($model) { $model->count--; if ($model->count < 1) { $model->delete(); } else { if ($model->count > $goods->surplus) { $model->count = $goods->surplus; } if (!$model->save(false)) { return $output; } } } $output = ['status' => 'success', 'data' => ['name' => $goods->name, 'price' => $goods->price, 'surplus' => $goods->surplus, 'cart' => $model ? $model->count : 0]]; return $output; }
public function actionDetail($id) { $model = Goods::findOne(['id' => $id, 'status' => Goods::STATUS_NORMAL]); if (!$model) { throw new NotFoundHttpException('未找到该商品'); } $output = ['status' => 'ok', 'name' => $model->name, 'price' => $model->price, 'surplus' => $model->surplus, 'description' => '【笑e购】' . $model->description, 'cart' => Yii::$app->user->isGuest ? 0 : Yii::$app->user->identity->getCartGoodsQuantity($id), 'image' => $model->images ? Url::toGoods($model->images[0]->name) : Yii::$app->params['goods.defaultImageUrl']]; Yii::$app->response->format = Response::FORMAT_JSON; return $output; }
public function actionIndex($cid = '') { $key = Yii::$app->request->get('key'); if ($key) { $where = ['like', 'name', $key]; } else { $where = []; } $query = Goods::find()->where($where); $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['defaultPageSize' => Yii::$app->params['defaultPageSizeProduct']], 'sort' => ['defaultOrder' => ['created_at' => SORT_DESC]]]); return $this->render('index', ['models' => $dataProvider->getModels(), 'pagination' => $dataProvider->pagination, 'totalItems' => $dataProvider->getTotalCount()]); }
/** * 从某个商品创建副本 * * @param string $goodsId * @return ApplyGoods */ public static function createDuplicate($goodsId) { $goods = Goods::findOne($goodsId); $model = new self(); $model->goods_id = $goodsId; $model->name = $goods->name; $model->category = $goods->category->name; $model->price = $goods->price; $model->cover = $goods->cover; $model->unit = $goods->unit; return $model; }
/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Goods::find(); $dataProvider = new ActiveDataProvider(['query' => $query]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere(['id' => $this->id, 'category_id' => $this->category_id, 'type_id' => $this->type_id, 'brand_id' => $this->brand_id, 'account_count' => $this->account_count, 'status' => $this->status, 'modified_time' => $this->modified_time, 'create_time' => $this->create_time]); $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'unit', $this->unit])->andFilterWhere(['like', 'thumbnail', $this->thumbnail])->andFilterWhere(['like', 'attributes', $this->attributes])->andFilterWhere(['like', 'show_pictures', $this->show_pictures])->andFilterWhere(['like', 'seo_title', $this->seo_title])->andFilterWhere(['like', 'seo_keyword', $this->seo_keyword])->andFilterWhere(['like', 'seo_description', $this->seo_description])->andFilterWhere(['like', 'detail_link', $this->detail_link])->andFilterWhere(['like', 'goods_sku', $this->goods_sku]); return $dataProvider; }
/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Goods::find(); $dataProvider = new ActiveDataProvider(['query' => $query]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere(['id' => $this->id, 'rubric_id' => $this->rubric_id, 'price' => $this->price]); $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'image', $this->image])->andFilterWhere(['like', 'description', $this->description]); return $dataProvider; }
/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Goods::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, 'price' => $this->price, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at]); $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'guige', $this->guige])->andFilterWhere(['like', 'danwei', $this->danwei])->andFilterWhere(['like', 'beizhu', $this->beizhu]); return $dataProvider; }
/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Goods::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, 'price' => $this->price, 'category_id' => $this->category_id, 'quantity' => $this->quantity, 'status' => $this->status]); $query->andFilterWhere(['like', 'item', $this->item])->andFilterWhere(['like', 'descr', $this->descr]); return $dataProvider; }
public function actionAdd($id) { Yii::$app->response->format = Response::FORMAT_JSON; if (!Goods::find()->where(['id' => $id, 'store_id' => Yii::$app->user->identity->store_id, 'status' => [Goods::STATUS_NORMAL, Goods::STATUS_OFF_SHELVES]])->exists() || Purchase::hasGoods($id)) { throw new BadRequestHttpException('拒绝操作。'); } $model = new Purchase(); $model->goods_id = $id; $model->store_id = Yii::$app->user->identity->store_id; $model->count = 1; if ($model->save(false)) { return ['status' => 'success', 'data' => []]; } else { return ['status' => 'fail', 'data' => ['message' => '加入失败。']]; } }
public function search($params) { $query = Goods::find()->where(['and', ['store_id' => Yii::$app->user->identity->store_id], ['<>', 'status', Goods::STATUS_DELETED]]); $dataProvider = new ActiveDataProvider(['query' => $query, 'sort' => ['defaultOrder' => ['id' => SORT_DESC]], 'pagination' => ['pageSize' => 20]]); // load the seach form data and validate if (!($this->load($params) && $this->validate())) { return $dataProvider; } $this->_addDigitalFilter($query, 'price'); $this->_addDigitalFilter($query, 'sales'); $this->_addDigitalFilter($query, 'surplus'); $dateBegin = strtotime($this->date); $dateEnd = $dateBegin + 86400; // adjust the query by adding the filters $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['category_id' => $this->category_id])->andFilterWhere(['like', 'unit', $this->unit])->andFilterWhere(['status' => $this->status])->andFilterWhere(['>=', 'created_at', $this->date ? $dateBegin : null])->andFilterWhere(['<', 'created_at', $this->date ? $dateEnd : null]); return $dataProvider; }
/* @var $this yii\web\View */ /* @var $searchModel common\models\GoodsPriceLogSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = '价格变动日志'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="goods-price-log-index"> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <p> <?php echo Html::a('添加', ['create'], ['class' => 'btn btn-success']); ?> </p> <?php echo GridView::widget(['dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [['class' => 'yii\\grid\\SerialColumn'], 'id', ['attribute' => 'goods_id', 'value' => function ($model) { $goods = \common\models\Goods::findModel($model->id); if ($goods) { return $goods->name; } else { return ""; } }], 'price', 'created_at:datetime', ['class' => 'yii\\grid\\ActionColumn']]]); ?> </div>
use yii\helpers\Url; /* @var $this yii\web\View */ /* @var $searchModel common\models\OrderSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Заказы'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="order-index"> <h1><?php echo Html::encode($this->title); ?> </h1> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <?php echo GridView::widget(['dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [['class' => 'yii\\grid\\SerialColumn'], 'id', ['label' => 'Товар', 'format' => 'raw', 'attribute' => 'goods_id', 'value' => function ($model) { return Html::a($model->goods->name, ['view', 'id' => $model->id]); }, 'filter' => Html::activeDropDownList($searchModel, 'goods_id', ArrayHelper::map(\common\models\Goods::find()->asArray()->all(), 'id', 'name'), ['class' => 'form-control', 'prompt' => 'Выберите товар'])], ['label' => 'Пользователь', 'attribute' => 'user_id', 'value' => function ($model) { return $model->user->username; }, 'filter' => Html::activeDropDownList($searchModel, 'user_id', ArrayHelper::map(\common\models\User::find()->asArray()->all(), 'id', 'username'), ['class' => 'form-control', 'prompt' => 'Выберите пользователя'])], 'datetime', ['label' => 'Статус', 'attribute' => 'active', 'value' => function ($model) { return $model->active ? "Новый" : "Выполнен"; }, 'filter' => Html::activeDropDownList($searchModel, 'active', [0 => 'Выполнен', 1 => "Новый"], ['class' => 'form-control', 'prompt' => 'Выберите статус'])], ['label' => 'Действие', 'attribute' => '', 'format' => 'raw', 'value' => function ($model) { return $model->active == 1 ? Html::a("Принять", ['accept', 'id' => $model->id]) : ''; }], ['class' => 'yii\\grid\\ActionColumn', 'template' => '{view}']]]); ?> </div>
* QQ:6232967 * Create at 2015-12-30 17:47:31 */ ?> <div class="rmzt"> <div class="rmzt-tit lm-tb"><span><a href="<?php echo Yii::$app->urlManager->createUrl(['price/index']); ?> ">更多</a></span>建筑材料信息价</div> <div><img src="<?php echo Yii::$app->params['staticsPath']; ?> images/yubin_55.jpg" width="280" height="104" alt="" /></div> <ul class="kbxx-nr"> <?php $goods = \common\models\Goods::find()->orderBy(['updated_at' => SORT_DESC])->limit(11)->all(); ?> <?php foreach ($goods as $k => $v) { ?> <li><a href="<?php echo Yii::$app->urlManager->createUrl(['price/index', 'key' => $v->name]); ?> "><?php echo date("Y", $v->updated_at); ?> 年<?php echo date("m", $v->updated_at); ?> 月<?php echo $v->name;
/** * @return \yii\db\ActiveQuery */ public function getGoods() { return $this->hasMany(Goods::className(), ['cat_id' => 'cat_id']); }
public function actionAddToComparelist() { $arrResult = []; $good_id = Yii::$app->request->post('good_id'); Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $isItemInCompareList = Compare::_isItemAlreadyIn($good_id, Yii::$app->session->id); if ($isItemInCompareList) { $arrResult['error'] = 'Товар уже в списке сравнений'; return $arrResult; } $model = new Compare(); $model->ip = Yii::$app->session->id; $model->goods_id = $good_id; $model->created_at = time(); $model->price = Goods::getPriceById($good_id); $model->category_id = Goods::getCategoryById($good_id); $model->brend_id = Goods::getBrendById($good_id) ? Goods::getBrendById($good_id) : null; //$model->validate(); //vd($model->getErrors()); if ($model->save()) { $arrResult['success'] = 'Товар добавлен в список сравнения!'; $quantityInCompareList = count(Compare::getListByIp(Yii::$app->session->id)); $arrResult['quantity'] = $quantityInCompareList; } else { //$model->validate(); //vd($model->getErrors()); $arrResult['error'] = 'Ошибка добавления товара!'; } return $arrResult; }
?> </p> <div class="row"> <div class="col-lg-12"> <?php Pjax::begin(); ?> <?php echo GridView::widget(['dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'tableOptions' => ['class' => 'table table-striped table-bordered table-center'], 'summaryOptions' => ['tag' => 'p', 'class' => 'text-right text-info'], 'columns' => [['class' => 'yii\\grid\\SerialColumn', 'headerOptions' => ['class' => '']], ['attribute' => 'name', 'headerOptions' => ['class' => 'col-md-2'], 'filterInputOptions' => ['class' => 'form-control input-sm']], ['attribute' => 'category_id', 'headerOptions' => ['class' => 'col-md-1'], 'filter' => Category::getKeyValuePairs(), 'filterInputOptions' => ['class' => 'form-control input-sm'], 'value' => function ($model, $key, $index, $column) { return $model->category->name; }], ['attribute' => 'store_id', 'headerOptions' => ['class' => 'col-md-2'], 'filterInputOptions' => ['class' => 'form-control input-sm'], 'value' => function ($model, $key, $index, $column) { return $model->store->school->name . '-' . $model->store->name; }, 'filter' => Select2::widget(['model' => $searchModel, 'initValueText' => ($store = Store::findOne($searchModel->store_id)) ? $store->name : '', 'attribute' => 'store_id', 'size' => Select2::SMALL, 'theme' => Select2::THEME_KRAJEE, 'options' => ['placeholder' => '搜索店铺名称...'], 'pluginOptions' => ['allowClear' => true, 'minimumInputLength' => 3, 'ajax' => ['url' => Url::to(['/store/name-filter']), 'dataType' => 'json', 'data' => new JsExpression('function(params) { return {q:params.term}; }')], 'escapeMarkup' => new JsExpression('function (markup) { return markup; }'), 'templateResult' => new JsExpression('function (store) { return store.text; }'), 'templateSelection' => new JsExpression('function (store) { return store.text; }')]])], ['attribute' => 'price', 'headerOptions' => ['class' => 'col-md-1'], 'format' => 'html', 'filterInputOptions' => ['class' => 'form-control input-sm', 'title' => '支持运算符'], 'value' => function ($model, $key, $index, $column) { return '¥ ' . $model->price; }], ['attribute' => 'surplus', 'headerOptions' => ['class' => 'col-md-1'], 'filterInputOptions' => ['class' => 'form-control input-sm', 'title' => '支持运算符']], ['attribute' => 'sales', 'headerOptions' => ['class' => 'col-md-1'], 'filterInputOptions' => ['class' => 'form-control input-sm', 'title' => '支持运算符']], ['attribute' => 'status', 'format' => 'raw', 'filter' => Goods::getStatusList(), 'filterInputOptions' => ['class' => 'form-control input-sm'], 'headerOptions' => ['class' => 'col-md-1'], 'value' => function ($model, $key, $index, $column) { return Html::dropDownList('status', $model->status, Goods::getStatusList(), ['data-id' => $model->id]); }], ['attribute' => 'created_at', 'format' => ['date', 'php:Y-m-d H:i'], 'filter' => DatePicker::widget(['model' => $searchModel, 'type' => DatePicker::TYPE_COMPONENT_APPEND, 'attribute' => 'date', 'options' => ['class' => 'input-sm'], 'pluginOptions' => ['autoclose' => true, 'format' => 'yyyy-mm-dd']]), 'headerOptions' => ['class' => 'col-md-2']], ['class' => 'yii\\grid\\ActionColumn', 'header' => '操作', 'headerOptions' => ['class' => 'col-md-1'], 'template' => '{update} {img} {surplus}', 'buttons' => ['img' => function ($url, $model, $key) { return Html::a('<span class="glyphicon glyphicon-picture" aria-hidden="true"></span>', $url, ['title' => '更新图片']); }, 'surplus' => function ($url, $model, $key) { return Html::a('<span class="glyphicon glyphicon-equalizer" aria-hidden="true"></span>', $url, ['title' => '库存变化记录']); }]]]]); ?> <?php Pjax::end(); ?> </div> </div> <?php $url = Url::to(['/goods/status']); $js = <<<JS var handle = function () {
public function actionHot($goods_id, $status = 1) { if (!$this->is_access('goods/update')) { exit; } $model = new Goods(); if ($model->setHot($goods_id, $status)) { echo '1'; } else { echo '0'; } }
<?php } ?> </ul> </div> <div class="tab-content"> <?php foreach ($modelGoodsCategories as $cat) { ?> <div class="tab-pane fade active in" id="<?php echo str_replace(' ', '', $cat->name); ?> "> <?php $goodsOfCategotyId = Goods::getGoodsByCategoriId($cat->id); ?> <?php if ($goodsOfCategotyId) { ?> <?php foreach ($goodsOfCategotyId as $good) { ?> <div class="col-sm-3"> <div class="product-image-wrapper"> <div class="single-products"> <div class="productinfo text-center"> <a href="/shop/detail?item=<?php echo $good->id; ?> "><img src="<?php
public function setHot($goods_id, $status = 1) { if (!in_array($status, [0, 1])) { return false; } return Goods::updateAll(['is_hot' => $status], 'goods_id = :goods_id', [':goods_id' => $goods_id]); }
/** * 更新配置文件的sitemap * @param string $config */ public static function updateConfigSitemap($config, $sm, $domain, $today) { if (!static::updateAll(['value' => serialize($config)], "code='sitemap'")) { return false; } $res = Category::find()->select(['id', 'cat_name'])->orderBy('parent_id')->column(); foreach ($res as $row) { $smi =& new GoogleSitemapItem($domain . UtilD::build_uri('category', [$row['id']], $row['cat_name']), $today, $config['category_changefreq'], $config['category_priority']); $sm->add_item($smi); } $res = ArticleCat::find()->select(['id', 'cat_name'])->where(['cat_type' => 1])->column(); foreach ($res as $row) { $smi =& new GoogleSitemapItem($domain . UtilD::build_uri('article_cat', ['acid' => $row['id']], $row['cat_name']), $today, $config['category_changefreq'], $config['category_priority']); $sm->add_item($smi); } $res = Goods::find()->select(['id', 'goods_name'])->where('is_delete=0')->column(); foreach ($res as $row) { $smi =& new GoogleSitemapItem($domain . UtilD::build_uri('goods', ['gid' => $row['id']], $row['goods_name']), $today, $config['content_changefreq'], $config['content_priority']); $sm->add_item($smi); } //文章 $res = Article::find()->select(['id', 'title', 'file_url', 'open_type'])->where('is_open=1')->column(); foreach ($res as $row) { $article_url = $row['open_type'] != 1 ? UtilD::build_uri('article', ['aid' => $row['id']], $row['title']) : trim($row['file_url']); $smi =& new GoogleSitemapItem($domain . $article_url, $today, $config['content_changefreq'], $config['content_priority']); $sm->add_item($smi); } $sm_file = 'sitemaps.xml'; if ($sm->build($sm_file)) { return true; } else { } }
/** * Finds the Goods model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Goods the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Goods::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }
public function actionCart() { $session = Yii::$app->getSession(); $cart = $session->has('cart') ? $session->get('cart') : []; $goods_id = ArrayHelper::getColumn($cart, 'id'); $goods = Goods::find()->where(['id' => $goods_id])->asArray()->indexBy('id')->all(); $amount = 0; foreach ($cart as $one_goods) { $amount += $one_goods['count'] * $goods[$one_goods['id']]['price']; } return $this->render('cart', ['cart' => $cart, 'goods' => $goods, 'amount' => $amount]); }
public static function getVolumeByStoreId($storeId) { $sql = 'SELECT sum(t0.count * t1.price) FROM ' . static::tableName() . ' AS t0 LEFT JOIN ' . Goods::tableName() . ' AS t1 ON t0.goods_id = t1.id WHERE t0.store_id=:store_id;'; $volume = Yii::$app->db->createCommand($sql, [':store_id' => $storeId])->queryScalar(); return bcadd($volume, '0', 2); }
public function getGoodsCount() { return Goods::find()->where(['store_id' => $this->id, 'status' => Goods::STATUS_NORMAL])->count(); }
use yii\bootstrap\ActiveForm; use common\models\Goods; $this->title = $model->isNewRecord ? '添加商品' : '更新商品'; ?> <div class="row"> <div class="col-lg-6"> <?php $form = ActiveForm::begin(); ?> <?php echo $form->field($model, 'name'); ?> <?php echo $form->field($model, 'description')->textarea(); ?> <?php echo $form->field($model, 'is_new')->dropDownList(Goods::getIsNewList()); ?> <?php echo $form->field($model, 'is_hot')->dropDownList(Goods::getIsHotList()); ?> <div class="form-group"> <?php echo Html::submitButton('<i class="fa fa-floppy-o"></i> 保存', ['class' => 'btn btn-primary']); ?> </div> <?php ActiveForm::end(); ?> </div> </div>
public function actionSurplus($id) { /* @var $model Goods */ $model = Goods::findOne(['id' => $id, 'store_id' => Yii::$app->user->identity->store_id]); if (!$model) { throw new NotFoundHttpException('未找到该商品。'); } $dataProvider = new ActiveDataProvider(['query' => GoodsSurplus::find()->where(['goods_id' => $id]), 'sort' => ['defaultOrder' => ['id' => SORT_DESC]], 'pagination' => ['pageSize' => 20]]); return $this->render('surplus', ['model' => $model, 'dataProvider' => $dataProvider]); }
} ?> <?php echo $form->field($model, 'sales'); ?> <?php echo $form->field($model, 'unit'); ?> <?php echo $form->field($model, 'is_new')->dropDownList(Goods::getIsNewList()); ?> <?php echo $form->field($model, 'is_hot')->dropDownList(Goods::getIsHotList()); ?> <?php echo $form->field($model, 'is_promotion')->dropDownList(Goods::getIsPromotionList()); ?> <div class="form-group"> <?php echo Html::submitButton('<i class="fa fa-floppy-o"></i> 保存', ['class' => 'btn btn-primary']); ?> <?php echo $model->isNewRecord ? '' : Html::a('更新商品图片', ['/goods/img', 'id' => $model->id], ['class' => 'text-warning']); ?> </div> <?php ActiveForm::end(); ?> </div> </div> <?php
/** * @return \yii\db\ActiveQuery */ public function getGoods() { return $this->hasOne(Goods::className(), ['id' => 'goods_id']); }
/** * 将商品从一个店铺克隆到另一个店铺 * * @param string $from 源商品所在店铺ID * @param string $to 目标店铺ID * @param string $category 过滤商品类型 * @param string $status 过滤商品状态 * @return string */ public function actionCloneAll($from, $to, $category = 'all', $status = 'all') { $modelFrom = Store::findOne($from); $modelTo = Store::findOne($to); if (!$modelFrom || !$modelTo) { echo "The parameter error.\n"; return static::EXIT_CODE_ERROR; } if ($modelFrom->type !== $modelTo->type) { if (!static::confirm("The types of two stores are not the same, continue?")) { echo "Cancelled.\n"; return static::EXIT_CODE_NORMAL; } } unset($modelFrom, $modelTo); $query = Goods::find()->where(['store_id' => $from]); if ($category !== 'all') { $modelCate = Category::findOne(['slug' => $category]); if ($modelCate) { $query->andWhere(['category_id' => $modelCate->id]); unset($modelCate); } else { echo "The category \"{$category}\" can not be exists.\n"; return static::EXIT_CODE_ERROR; } } if ($status !== 'all') { if (in_array($status, [Goods::STATUS_NORMAL, Goods::STATUS_OFF_SHELVES, Goods::STATUS_DELETED])) { $query->andWhere(['status' => $status]); } else { echo "The status was error.\n"; return static::EXIT_CODE_ERROR; } } if (($count = $query->count()) > 0) { if (!static::confirm("Next we will clone {$count} goods, are you sure?")) { echo "Cancelled.\n"; return static::EXIT_CODE_NORMAL; } } else { echo "The goods count is 0.\n"; return static::EXIT_CODE_NORMAL; } $goodsList = $query->asArray()->all(); $time = time(); $sql = "INSERT INTO {{%goods}} (name, store_id, category_id, cover, price, price_original, cost, description, status, surplus, sales, unit, is_new, is_hot, is_promotion, created_at, updated_at) VALUES (:name, :store_id, :category_id, :cover, :price, :price_original, :cost, :description, :status, :surplus, :sales, :unit, :is_new, :is_hot, :is_promotion, :created_at, :updated_at)"; $sql2 = "INSERT INTO {{%goods_img}} (name, goods_id) VALUES (:name, :goods_id)"; $sql3 = "INSERT INTO {{%goods_surplus}} (goods_id, surplus_before, amount, surplus_after, remark, created_at, updated_at) VALUES (:goods_id, :surplus_before, :amount, :surplus_after, :remark, :created_at, :updated_at)"; $transaction = Yii::$app->db->beginTransaction(); try { foreach ($goodsList as $goods) { Yii::$app->db->createCommand($sql, [':name' => $goods['name'], ':store_id' => $to, ':category_id' => $goods['category_id'], ':cover' => $goods['cover'], ':price' => $goods['price'], ':price_original' => $goods['price_original'], ':cost' => $goods['cost'], ':description' => $goods['description'], ':status' => $goods['status'], ':surplus' => $goods['surplus'], ':sales' => '0', ':unit' => $goods['unit'], ':is_new' => $goods['is_new'], ':is_hot' => $goods['is_hot'], ':is_promotion' => $goods['is_promotion'], ':created_at' => $time, ':updated_at' => $time])->execute(); $goodsId = Yii::$app->db->getLastInsertID(); $goodsImgList = GoodsImg::find()->where(['goods_id' => $goods['id']])->asArray()->all(); foreach ($goodsImgList as $goodsImg) { Yii::$app->db->createCommand($sql2, [':name' => $goodsImg['name'], ':goods_id' => $goodsId])->execute(); } Yii::$app->db->createCommand($sql3, [':goods_id' => $goodsId, ':surplus_before' => 0, ':amount' => $goods['surplus'], ':surplus_after' => $goods['surplus'], ':remark' => '初始化库存。', ':created_at' => $time, ':updated_at' => $time])->execute(); } $transaction->commit(); echo "Success!\n"; return static::EXIT_CODE_NORMAL; } catch (\Exception $e) { $transaction->rollBack(); echo $e->getMessage(); return static::EXIT_CODE_ERROR; } }