BcModelTrait.php 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. <?php
  2. namespace crmeb\traits;
  3. trait BcModelTrait
  4. {
  5. public static function bcInc($key, $incField, $inc, $keyField = null, $acc = 2)
  6. {
  7. if (!is_numeric($inc)) return false;
  8. $model = new self();
  9. if ($keyField === null) $keyField = $model->getPk();
  10. $result = self::where($keyField, $key)->field([$keyField, $incField])->find();
  11. if (!$result) return false;
  12. $new = bcadd($result[$incField], $inc, $acc);
  13. return false !== $model->where($keyField, $key)->update([$incField => $new]);
  14. }
  15. public static function bcDec($key, $decField, $dec, $keyField = null, $minus = false, $acc = 2)
  16. {
  17. if (!is_numeric($dec)) return false;
  18. $model = new self();
  19. if ($keyField === null) $keyField = $model->getPk();
  20. $result = self::where($keyField, $key)->field([$keyField, $decField])->find();
  21. if (!$result) return false;
  22. $new = bcsub($result[$decField], $dec, $acc);
  23. if (!$minus && $new < 0) return false;
  24. return false !== $model->where($keyField, $key)->update([$decField => $new]);
  25. }
  26. }