123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- <?php
- namespace app\cxinv\model;
- use think\model\concern\SoftDelete;
- class ProductsCombind extends Base
- {
- use SoftDelete;
- //设置字段信息
- protected $schema = [
- 'id' =>'bigint',//
- 'parent_id' =>'bigint',//组合商品id
- 'child_id' =>'bigint',//子商品id
- 'skuCode' =>'varchar',//订单商品编号
- 'child_num' =>'int',//子商品每单位对应数量
- 'create_time' =>'datetime',//
- 'delete_time' =>'datetime',//
- ];
- protected $createTime = 'create_time';
- protected $updateTime = false;
- protected $deleteTime = 'delete_time';
- public function Products(){
- return $this->hasOne(FinancialProducts::class,'id','child_id');
- }
- public function ProductStock(){
- return $this->hasMany(FinancialProducts::class,'skuCode','skuCode')->bind(['residue_stock','total_stock','pending_stock','combind_stock']);
- }
- public static function CombindSubStock($pid,$num,$type=1){
- $list = self::where('parent_id',$pid)->select();
- if($list->isEmpty()) throw new \Exception('组合商品不存在');
- $productID = [];
- foreach ($list as $k=>$v){
- $where = $type==1? ['skuCode'=>$v['skuCode'],"basic_status"=>1] : ['skuCode'=>$v['skuCode']];
- $stock=FinancialProducts::with(['ProductStock'])->where($where)->select();
- if($stock->isEmpty()) throw new \Exception('组合商品子商品不存在');
- $child_num = bcmul($v['child_num'],$num,8);
- $total= count($stock);
- $stock->each(function ($item,$key) use (&$productID,&$child_num,$total,$type){
- if($item->residue_stock > $child_num || ($type==2 && $total==$key+1)) {
- $sub_stock = $child_num;
- $child_num = "0";
- }else{
- $child_num = bcsub($child_num,$item->residue_stock,8);
- $sub_stock = $item->residue_stock;
- }
- $productID[] = ['product_id' => $item->id, 'type'=>2,'num' => $sub_stock];
- if($child_num == "0") return false;
- });
- if($child_num > 0 && $type==1) throw new \Exception('组合商品子商品库存不足');
- }
- return $productID;
- }
- }
|