PartsStock.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace addons\qingdongams\model;
  3. use think\Exception;
  4. use think\Model;
  5. use traits\model\SoftDelete;
  6. /**
  7. *产品库存记录
  8. */
  9. class PartsStock extends Model
  10. {
  11. use SoftDelete;
  12. protected $name = 'qingdongams_parts_stock';
  13. // 开启自动写入时间戳字段
  14. protected $autoWriteTimestamp = 'int';
  15. // 定义时间戳字段名
  16. protected $createTime = 'createtime';
  17. protected $updateTime = 'updatetime';
  18. protected $deleteTime = 'deletetime';
  19. protected $hidden = ['deletetime', 'updatetime'];
  20. public function parts()
  21. {
  22. return $this->hasOne(Parts::class, 'id', 'parts_id')->field('id,name');
  23. }
  24. //创建人
  25. public function createStaff()
  26. {
  27. return $this->hasOne(Staff::class, 'id', 'create_staff_id')->field('id,name,img');
  28. }
  29. public function getCreatetimeAttr($value)
  30. {
  31. return date('Y-m-d H:i', $value);
  32. }
  33. //添加库存记录
  34. public static function addStock($params)
  35. {
  36. $model = new self;
  37. // 调用当前模型对应的User验证器类进行数据验证
  38. $result = $model->allowField(true)->save($params);
  39. $lastId = $model->getLastInsID();
  40. if (false === $result) {
  41. // 验证失败 输出错误信息
  42. throw new Exception($model->getError());
  43. }
  44. if ($params['type'] == 1) {
  45. if (Parts::where(['id' => $params['parts_id']])->setInc('stock', $params['number']) == false) {
  46. throw new Exception('新增库存失败');
  47. }
  48. } elseif ($params['type'] == 2) {
  49. if (Parts::where(['id' => $params['parts_id']])->setDec('stock', $params['number']) == false) {
  50. throw new Exception('新增库存失败');
  51. }
  52. }
  53. return $lastId;
  54. }
  55. }