public function add($data, $before_id = null) { if (empty($data)) { return false; } $before = null; if ($before_id) { $before = $this->getById($before_id); } if (!$before) { $sort = $this->query("SELECT MAX(sort) AS sort FROM {$this->table}")->fetchField('sort') + 1; } else { $this->query("UPDATE {$this->table} SET sort = sort + 1 WHERE sort >= {$before['sort']}"); $sort = (int) $before['sort']; } if (empty($data['low_count'])) { $data['low_count'] = shopStockModel::LOW_DEFAULT; } if (empty($data['critical_count'])) { $data['critical_count'] = shopStockModel::CRITICAL_DEFAULT; } $data['sort'] = $sort; $id = $this->insert($data); $product_stocks_model = new shopProductStocksModel(); $product_stocks_model->insertZeros($id); $product_model = new shopProductModel(); $product_model->correctCount(); return $id; }
/** * Delete stock with or not recounting total counter of skus * * @param int $stock_id * @param boolean $recount */ public function deleteStock($stock_id, $recount = true) { $stock_id = (int) $stock_id; $stock_model = new shopStockModel(); $stock = $stock_model->getById($stock_id); $stock_name = $stock ? $stock['name'] : ''; if ($stock_id) { if ($recount) { $sql = "UPDATE `shop_product_skus` s\n JOIN `{$this->table}` ps ON s.id = ps.sku_id\n SET s.count = s.count - ps.count\n WHERE ps.stock_id = {$stock_id}"; if (!$this->exec($sql)) { return false; } $sql = "UPDATE `shop_product` p\n JOIN (\n SELECT product_id, SUM(count) count\n FROM {$this->table}\n WHERE stock_id = {$stock_id}\n GROUP BY product_id\n ) AS ps ON p.id = ps.product_id\n SET p.count = p.count - ps.count"; if (!$this->exec($sql)) { return false; } $product_model = new shopProductModel(); $product_model->correctCount(); } $log_model = new shopProductStocksLogModel(); $log_model->updateByField(array('stock_id' => $stock_id), array('stock_id' => null, 'stock_name' => $stock_name)); return $this->deleteByField('stock_id', $stock_id); } return false; }
<?php $stock_model = new shopStockModel(); $n = $stock_model->countAll(); if ($n > 0) { // repair invariant: all N stocks exists, but sku_cout IS NULL $sql = "\n UPDATE shop_product_skus s JOIN ( \n SELECT sk.id, SUM(st.count) cnt\n FROM shop_product_skus sk\n JOIN shop_product_stocks st ON sk.id = st.sku_id\n WHERE sk.count IS NULL\n GROUP BY sk.id\n HAVING COUNT( * ) = {$n}\n ) AS t ON s.id = t.id\n SET s.count = t.cnt"; $stock_model->exec($sql); $product_model = new shopProductModel(); $product_model->correctCount(); }