cxfoot/models/common/CommonCartEditForm.php
2023-10-24 14:54:18 +08:00

165 lines
4.3 KiB
PHP

<?php
/**
* @author Any
* @description KISS
* @date 2021年6月15日
* @version 1.0.0
*
* _____LOG_____
*
*/
namespace app\models\common;
use app\models\Cart;
use app\models\Model;
use app\models\GoodsAttr;
class CommonCartEditForm extends Model
{
public $list;
public $plugin_sign;
public $cx_mch_id;
public $user_id;
public function rules()
{
return [
[['list'], 'trim'],
[['cx_mch_id', 'user_id'], 'integer'],
[['list', 'cx_mch_id', 'user_id', 'plugin_sign'], 'required']
];
}
protected function secondArrayUniqueBykey($arr, $key, &$tmp)
{
$tmp_arr = [];
foreach ($arr as $k => $item) {
if (in_array($item[$key], $tmp_arr)) {
$re = array_search($item[$key], $tmp_arr);
unset($tmp_arr[$re]);
}
$tmp_arr[$k] = $item[$key];
}
foreach ($tmp_arr as $k => $item) {
if (array_key_exists($k, $arr)) {
$tmp[] = $arr[$k];
}
}
}
//批量更新
public function save()
{
if (!$this->validate()) {
return $this->getModelError();
};
try {
while (Cart::cacheStatusGet()) {
}
Cart::cacheStatusSet(true);
$info = json_decode($this->list, true);
if (!$info) {
throw new \Exception('数据为空');
}
//去重
$this->secondArrayUniqueBykey($info, 'attr', $list);
$array = [];
$t = \Yii::$app->db->beginTransaction();
foreach ($list as $item) {
$goodsAttr = $this->getGoodsAttr($item);
if (!$goodsAttr) {
continue;
}
if ($goodsAttr->stock < $item['num']) {
throw new \Exception('库存不足');
}
$form = Cart::findOne([
'goods_id' => $item['goods_id'],
'user_id' => $this->user_id,
'attr_id' => $item['attr'],
'is_delete' => 0
]);
if (isset($form) && $item['num'] > 0) {
$form->num = $item['num'];
$form->save();
continue;
} elseif (isset($form) && $item['num'] == 0) {
$form->is_delete = 1;
$form->save();
continue;
}
if ($item['num'] > 0) {
$array[] = [
$this->cx_mch_id,
$this->user_id,
$item['attr'],
$item['goods_id'],
$item['num'],
$this->plugin_sign,
0,
time(),
time(),
time(),
];
}
}
if (isset($array)) {
\Yii::$app->db->createCommand()
->batchInsert(
Cart::tableName(),
[
'cx_mch_id',
'user_id',
'attr_id',
'goods_id',
'num',
'plugin_sign',
'is_delete',
'created_at',
'updated_at',
'deleted_at'
],
$array
)
->execute();
}
$t->commit();
return $this->apiReturnSuccess();
} catch (\Exception $e) {
return $this->apiReturnError($e->getMessage());
}
}
protected function getGoodsAttr($item)
{
return GoodsAttr::find()->alias('c')->where([
'c.goods_id' => $item['goods_id'],
'c.id' => $item['attr'],
'c.is_delete' => 0,
])
->innerJoinWith('goods')
->one();
}
public function __destruct()
{
Cart::cacheStatusSet(false);
}
}