ProductsCombind.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace app\cxinv\model;
  3. use think\model\concern\SoftDelete;
  4. class ProductsCombind extends Base
  5. {
  6. use SoftDelete;
  7. //设置字段信息
  8. protected $schema = [
  9. 'id' =>'bigint',//
  10. 'parent_id' =>'bigint',//组合商品id
  11. 'child_id' =>'bigint',//子商品id
  12. 'skuCode' =>'varchar',//订单商品编号
  13. 'child_num' =>'int',//子商品每单位对应数量
  14. 'create_time' =>'datetime',//
  15. 'delete_time' =>'datetime',//
  16. ];
  17. protected $createTime = 'create_time';
  18. protected $updateTime = false;
  19. protected $deleteTime = 'delete_time';
  20. public function Products(){
  21. return $this->hasOne(FinancialProducts::class,'id','child_id');
  22. }
  23. public function ProductStock(){
  24. return $this->hasMany(FinancialProducts::class,'skuCode','skuCode')->bind(['residue_stock','total_stock','pending_stock','combind_stock']);
  25. }
  26. public static function CombindSubStock($pid,$num,$type=1){
  27. $list = self::where('parent_id',$pid)->select();
  28. if($list->isEmpty()) throw new \Exception('组合商品不存在');
  29. $productID = [];
  30. foreach ($list as $k=>$v){
  31. $where = $type==1? ['skuCode'=>$v['skuCode'],"basic_status"=>1] : ['skuCode'=>$v['skuCode']];
  32. $stock=FinancialProducts::with(['ProductStock'])->where($where)->select();
  33. if($stock->isEmpty()) throw new \Exception('组合商品子商品不存在');
  34. $child_num = bcmul($v['child_num'],$num,8);
  35. $total= count($stock);
  36. $stock->each(function ($item,$key) use (&$productID,&$child_num,$total,$type){
  37. if($item->residue_stock > $child_num || ($type==2 && $total==$key+1)) {
  38. $sub_stock = $child_num;
  39. $child_num = "0";
  40. }else{
  41. $child_num = bcsub($child_num,$item->residue_stock,8);
  42. $sub_stock = $item->residue_stock;
  43. }
  44. $productID[] = ['product_id' => $item->id, 'type'=>2,'num' => $sub_stock];
  45. if($child_num == "0") return false;
  46. });
  47. if($child_num > 0 && $type==1) throw new \Exception('组合商品子商品库存不足');
  48. }
  49. return $productID;
  50. }
  51. }