ProductStock.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. protected $append= ['combind_stock'];
  18. public function Product(){
  19. return $this->belongsTo(FinancialProducts::class,'product_id','id')->bind(['goodName','skuCode']);
  20. }
  21. public function getCombindStockAttr($value,$data){
  22. $isCombind=FinancialProducts::where('id',$data['product_id'])->value('is_combind');
  23. if($isCombind==1){
  24. $combind_stock=ProductsCombind::with(['ProductStock'=>['ProductStock']])->where('parent_id',$data['product_id'])->select();
  25. $num=0;
  26. $combind_stock->each(function ($item,$key) use (&$num){
  27. $child_num = $item->child_num;
  28. $Total_stock = array_sum(array_column($item->ProductStock->toArray(),'residue_stock'));
  29. $Parent_stock = bcdiv($Total_stock,$child_num,8);
  30. if($key==0) $num=$Parent_stock;
  31. elseif($Parent_stock<$num) $num=$Parent_stock;
  32. });
  33. return $num;
  34. }else{
  35. return 0;
  36. }
  37. }
  38. public static function AddStock($product_id,$num){
  39. $product=self::where("product_id",$product_id)->findOrEmpty();
  40. if(!$product->isEmpty()){
  41. $product->residue_stock=bcadd($product->residue_stock,$num,8);
  42. $product->total_stock=bcadd($product->total_stock,$num,8);
  43. $save=$product->save();
  44. if(!$save) throw new \Exception('库存添加失败');
  45. }else{
  46. $product_data=[
  47. 'product_id'=>$product_id,
  48. 'residue_stock'=>$num,
  49. 'total_stock'=>$num,
  50. ];
  51. $creste= self::create($product_data);
  52. if($creste->isEmpty()) throw new \Exception('库存添加失败');
  53. }
  54. return true;
  55. }
  56. /**
  57. * @param $product_id 商品id
  58. * @param $num 待出库数量
  59. * @param $type 1 正常出库 2 强制出库
  60. * @return true
  61. * @throws \Exception
  62. */
  63. public static function OutStock($product_id,$num,$type=1){
  64. $product=self::where("product_id",$product_id)->findOrEmpty();
  65. if(!$product->isEmpty()){
  66. if($product->residue_stock<$num && $type==1) throw new \Exception('库存不足');
  67. $product->residue_stock=bcsub($product->residue_stock,$num,8);
  68. $product->pending_stock=bcadd($product->pending_stock,$num,8);
  69. $save=$product->save();
  70. if(!$save) throw new \Exception('库存修改失败');
  71. }else{
  72. throw new \Exception('商品库存未找到'.$product_id);
  73. }
  74. return true;
  75. }
  76. }