1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- <?php
- namespace app\cxinv\model;
- class ProductStock extends Base
- {
- //设置字段信息
- protected $schema = [
- 'id' =>'bigint',//
- 'product_id' =>'bigint',//商品id
- 'residue_stock' =>'bigint',//剩余库存
- 'pending_stock' =>'bigint',//待出库存
- 'total_stock' =>'bigint',//总库存
- 'create_time' =>'datetime',//
- 'update_time' =>'datetime',//
- ];
- protected $createTime = 'create_time';
- protected $updateTime = 'update_time';
- protected $append= ['combind_stock'];
- public function Product(){
- return $this->belongsTo(FinancialProducts::class,'product_id','id')->bind(['goodName','skuCode']);
- }
- public function getCombindStockAttr($value,$data){
- $isCombind=FinancialProducts::where('id',$data['product_id'])->value('is_combind');
- if($isCombind==1){
- $combind_stock=ProductsCombind::with(['ProductStock'=>['ProductStock']])->where('parent_id',$data['product_id'])->select();
- $num=0;
- $combind_stock->each(function ($item,$key) use (&$num){
- $child_num = $item->child_num;
- $Total_stock = array_sum(array_column($item->ProductStock->toArray(),'residue_stock'));
- $Parent_stock = bcdiv($Total_stock,$child_num,8);
- if($key==0) $num=$Parent_stock;
- elseif($Parent_stock<$num) $num=$Parent_stock;
- });
- return $num;
- }else{
- return 0;
- }
- }
- public static function AddStock($product_id,$num){
- $product=self::where("product_id",$product_id)->findOrEmpty();
- if(!$product->isEmpty()){
- $product->residue_stock=bcadd($product->residue_stock,$num,8);
- $product->total_stock=bcadd($product->total_stock,$num,8);
- $save=$product->save();
- if(!$save) throw new \Exception('库存添加失败');
- }else{
- $product_data=[
- 'product_id'=>$product_id,
- 'residue_stock'=>$num,
- 'total_stock'=>$num,
- ];
- $creste= self::create($product_data);
- if($creste->isEmpty()) throw new \Exception('库存添加失败');
- }
- return true;
- }
- /**
- * @param $product_id 商品id
- * @param $num 待出库数量
- * @param $type 1 正常出库 2 强制出库
- * @return true
- * @throws \Exception
- */
- public static function OutStock($product_id,$num,$type=1){
- $product=self::where("product_id",$product_id)->findOrEmpty();
- if(!$product->isEmpty()){
- if($product->residue_stock<$num && $type==1) throw new \Exception('库存不足');
- $product->residue_stock=bcsub($product->residue_stock,$num,8);
- $product->pending_stock=bcadd($product->pending_stock,$num,8);
- $save=$product->save();
- if(!$save) throw new \Exception('库存修改失败');
- }else{
- throw new \Exception('商品库存未找到'.$product_id);
- }
- return true;
- }
- }
|