ProductStock.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace app\cxinv\model;
  3. class ProductStock extends Base
  4. {
  5. //设置字段信息
  6. protected $schema = [
  7. 'id' =>'bigint',//
  8. 'product_id' =>'bigint',//商品id
  9. 'residue_stock' =>'bigint',//剩余库存
  10. 'pending_stock' =>'bigint',//待出库存
  11. 'total_stock' =>'bigint',//总库存
  12. 'create_time' =>'datetime',//
  13. 'update_time' =>'datetime',//
  14. ];
  15. protected $createTime = 'create_time';
  16. protected $updateTime = 'update_time';
  17. public function Product(){
  18. return $this->belongsTo(FinancialProducts::class,'product_id','id')->bind(['goodName','skuCode']);
  19. }
  20. public static function AddStock($product_id,$num){
  21. $product=self::where("product_id",$product_id)->findOrEmpty();
  22. if(!$product->isEmpty()){
  23. $product->residue_stock=bcadd($product->residue_stock,$num,8);
  24. $product->total_stock=bcadd($product->total_stock,$num,8);
  25. $save=$product->save();
  26. if(!$save) throw new \Exception('库存添加失败');
  27. }else{
  28. $product_data=[
  29. 'product_id'=>$product_id,
  30. 'residue_stock'=>$num,
  31. 'total_stock'=>$num,
  32. ];
  33. $creste= self::create($product_data);
  34. if($creste->isEmpty()) throw new \Exception('库存添加失败');
  35. }
  36. return true;
  37. }
  38. public static function OutStock($product_id,$num,$type=1){
  39. $product=self::where("product_id",$product_id)->findOrEmpty();
  40. if(!$product->isEmpty()){
  41. if($product->residue_stock<$num && $type==1) throw new \Exception('库存不足');
  42. $product->residue_stock=bcsub($product->residue_stock,$num,8);
  43. $product->pending_stock=bcadd($product->pending_stock,$num,8);
  44. $save=$product->save();
  45. if(!$save) throw new \Exception('库存修改失败');
  46. }else{
  47. throw new \Exception('库存不足');
  48. }
  49. return true;
  50. }
  51. }