StoreProductLevel.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/12/13
  6. */
  7. namespace app\models\store;
  8. use crmeb\basic\BaseModel;
  9. use think\facade\Db;
  10. use crmeb\traits\ModelTrait;
  11. /**
  12. * TODO 产品属性Model
  13. * Class StoreProductAttr
  14. * @package app\models\store
  15. */
  16. class StoreProductLevel extends BaseModel
  17. {
  18. /**
  19. * 模型名称
  20. * @var string
  21. */
  22. protected $name = 'store_product_level';
  23. use ModelTrait;
  24. protected $autoWriteTimestamp = true;
  25. protected $createTime = 'add_time';
  26. protected $updateTime = 'update_time';
  27. /**
  28. * 获取商品的等级返利数据
  29. * @param int $productId 商品ID
  30. * @return array
  31. */
  32. public static function getProductLevelRebate($productId)
  33. {
  34. return self::where('product_id', $productId)->select()->toArray();
  35. }
  36. /**
  37. * 根据等级ID获取返利比例
  38. * @param int $productId 商品ID
  39. * @param int $levelId 等级ID
  40. * @return float|int
  41. */
  42. public static function getRebateRatio($productId, $levelId)
  43. {
  44. $rebate = self::where('product_id', $productId)->where('level_id', $levelId)->value('rebate_ratio');
  45. return $rebate !== null ? $rebate : 0;
  46. }
  47. /**
  48. * 批量保存商品等级返利数据
  49. * @param int $productId 商品ID
  50. * @param array $levelRebates 等级返利数据
  51. * @return bool
  52. */
  53. public static function saveProductLevelRebate($productId, $levelRebates)
  54. {
  55. // 开启事务
  56. self::beginTrans();
  57. try {
  58. // 删除原有数据
  59. self::where('product_id', $productId)->delete();
  60. // 插入新数据
  61. foreach ($levelRebates as $level) {
  62. self::create([
  63. 'product_id' => $productId,
  64. 'level_id' => $level['id'],
  65. 'rebate_ratio' => $level['rebate_ratio'],
  66. ]);
  67. }
  68. // 提交事务
  69. self::commitTrans();
  70. return true;
  71. } catch (\Exception $e) {
  72. // 回滚事务
  73. self::rollbackTrans();
  74. return false;
  75. }
  76. }
  77. }