* @day: 2017/12/13 */ namespace app\models\store; use crmeb\basic\BaseModel; use think\facade\Db; use crmeb\traits\ModelTrait; /** * TODO 产品属性Model * Class StoreProductAttr * @package app\models\store */ class StoreProductLevel extends BaseModel { /** * 模型名称 * @var string */ protected $name = 'store_product_level'; use ModelTrait; protected $autoWriteTimestamp = true; protected $createTime = 'add_time'; protected $updateTime = 'update_time'; /** * 获取商品的等级返利数据 * @param int $productId 商品ID * @return array */ public static function getProductLevelRebate($productId) { return self::where('product_id', $productId)->select()->toArray(); } /** * 根据等级ID获取返利比例 * @param int $productId 商品ID * @param int $levelId 等级ID * @return float|int */ public static function getRebateRatio($productId, $levelId) { $rebate = self::where('product_id', $productId)->where('level_id', $levelId)->value('rebate_ratio'); return $rebate !== null ? $rebate : 0; } /** * 批量保存商品等级返利数据 * @param int $productId 商品ID * @param array $levelRebates 等级返利数据 * @return bool */ public static function saveProductLevelRebate($productId, $levelRebates) { // 开启事务 self::beginTrans(); try { // 删除原有数据 self::where('product_id', $productId)->delete(); // 插入新数据 foreach ($levelRebates as $level) { self::create([ 'product_id' => $productId, 'level_id' => $level['id'], 'rebate_ratio' => $level['rebate_ratio'], ]); } // 提交事务 self::commitTrans(); return true; } catch (\Exception $e) { // 回滚事务 self::rollbackTrans(); return false; } } }