| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
- namespace App;
- use Illuminate\Database\Eloquent\Builder;
- use Illuminate\Database\Eloquent\Model;
- use App\Traits\ModelTimeFormat;
- class Commodity extends Model
- {
- use ModelTimeFormat;
- protected $fillable=['name','sku','owner_id','created_at','length','width','height','volumn',"type","pack_spec"];
- protected $appends=['barcode'];
- // protected $appends=['barcode','owner_name','owner_code'];
- public function setNameAttribute($value){
- $this->attributes['name']=str_replace(PHP_EOL,'',$value);
- }
- public function getNameAttribute($value){
- return str_replace(array("\r\n","\n","\r","\"","""),' ',$value);
- }
- public function barcodes()
- {
- return $this->hasMany('\App\CommodityBarcode');
- }
- public function owner(){
- return $this->belongsTo('App\Owner','owner_id','id');
- }
- public function getBarcodeAttribute(){
- return $this->barcodes[0]['code']??'';
- }
- public function getOwnerNameAttribute(){
- return $this->owner['name']??'';
- }
- public function getOwnerCodeAttribute(){
- return $this->owner['code']??'';
- }
- static function newCommodityBy_BarcodeOwnerIdNameSku($barcode,$ownerId,$name,$sku){
- $barcodes=rtrim($barcode,',');
- $barcodes=explode(',',$barcodes);
- foreach ($barcodes as $k=>$barcode){
- if(!trim($barcode)) unset($barcodes[$k]);
- }
- $commodities=[];
- foreach ($barcodes as $barcode){
- if(!trim($barcode))continue;
- $commodity=Commodity::whereHas('barcodes', function (Builder $query)use($barcode){
- $query->where('code',$barcode);
- })->where('name',$name)->where('owner_id',$ownerId)->first();
- if($commodity)$commodities[]=$commodity;
- }
- if(count($barcodes)==count($commodities)&&count($commodities)>0){//筛选掉仅有一个条码相等的。
- $commodity=$commodities[0];
- }else{
- $commodity=null;
- }
- if(!$commodity){
- $commodity=new Commodity(['name'=>$name,'sku'=>$sku,'owner_id'=>$ownerId]);
- $commodity->save();
- }else{
- if(!isset($commodity['name'])||(!isset($commodity['sku'])||$sku)){
- $commodity['name']=$name;
- $commodity['sku']=$sku;
- $commodity->save();
- }
- }
- foreach ($barcodes as $barcode){
- if(!trim($barcode))continue;
- $commodityBarcode=CommodityBarcode::where('code',$barcode)->where('commodity_id',$commodity['id'])->first();
- if(!$commodityBarcode){
- $commodityBarcode=new CommodityBarcode(['code'=>$barcode,'commodity_id'=>$commodity['id']]);
- $commodityBarcode->save();
- }
- }
- return $commodity;
- }
- public function newBarcode($barcode){
- $barcodeModel = $this->barcodes()->where('code', $barcode)->first();
- if(!$barcodeModel){
- return CommodityBarcode::query()->create(['commodity_id'=>$this['id'],'code'=>$barcode]);
- }
- return $barcodeModel;
- }
- }
|