[李景山php]每天laravel-20161201|BelongsToMany.php-4
//2016-09-23/***FormatthesynclistsothatitiskeyedbyID.**@paramarray$records*@returnarray*/protectedfunctionformatSyncList(array$records){//formatthesynclistsothatitiskeyedbID.$results=[];//setreturnvaluesforeach($recordsas$id=>$attributes){//loopthisrecordsif(!is_array($attributes)){//getIDandattributeslist($id,$attributes)=[$attributes,[]];}//setlist$results[$id]=$attributes;}////settheresultbyidthrowtheattributesreturn$results;}//returnresults/***AttachalloftheIDsthataren'tinthecurrentarray.**@paramarray$records*@paramarray$current*@parambool$touch*@returnarray*/protectedfunctionattachNew(array$records,array$current,$touch=true){//AttachalloftheIDsthataren'tinthecurrentarray.$changes=['attached'=>[],'updated'=>[]];//setthechangesforeach($recordsas$id=>$attributes){//looptherecords//IftheIDisnotinthelistofexistingpivotIDs,wewillinsertanewpivot//record,otherwise,wewilljustupdatethisexistingrecordonthisjoining//table,sothatthedeveloperswilleasilyupdatetheserecordspainfree.if(!in_array($id,$current)){//ifthisidnotinthepivotgroup,justinsertit.$this->attach($id,$attributes,$touch);$changes['attached'][]=is_numeric($id)?(int)$id:(string)$id;}//Nowwe'lltrytoupdateanexistingpivotrecordwiththeattributesthatwere//giventothemethod.Ifthemodelisactuallyupdatedwewilladdittothe//listofupdatedpivotrecordssowereturnthembackouttotheconsumer.elseif(count($attributes)>0&&$this->updateExistingPivot($id,$attributes,$touch)){$changes['updated'][]=is_numeric($id)?(int)$id:(string)$id;}//wereturnthembackouttotheconsumer.}return$changes;}/***Updateanexistingpivotrecordonthetable.**@parammixed$id*@paramarray$attributes*@parambool$touch*@returnint*/publicfunctionupdateExistingPivot($id,array$attributes,$touch=true){//Updateanexistingpivotrecordonthetableif(in_array($this->updatedAt(),$this->pivotColumns)){$attributes=$this->setTimestampsOnAttach($attributes,true);}//in_array($this->updateAt)//settheattribute$updated=$this->newPivotStatementForId($id)->update($attributes);//getthisupdatedif($touch){$this->touchIfTouching();}//ifneedtouchreturn$updated;}//returnthisresult/***Attachamodeltotheparent.**@parammixed$id*@paramarray$attributes*@parambool$touch*@returnvoid*/publicfunctionattach($id,array$attributes=[],$touch=true){if($idinstanceofModel){$id=$id->getKey();}//case1if($idinstanceofCollection){$id=$id->modelKeys();}//case2$query=$this->newPivotStatement();//getthequery$query->insert($this->createAttachRecords((array)$id,$attributes));//insertthedataif($touch){$this->touchIfTouching();}//touchsomething}//firsttoattach/***Createanarrayofrecordstoinsertintothepivottable.**@paramarray$ids*@paramarray$attributes*@returnarray*/protectedfunctioncreateAttachRecords($ids,array$attributes){//Createanarrayofrecordstoinsertintothepivottable.$records=[];//records$timed=($this->hasPivotColumn($this->createdAt())||$this->hasPivotColumn($this->updatedAt()));//settimed//Tocreatethep_w_uploadrecords,wewillsimplyspinthroughtheIDsgiven//andcreateanewrecordtoinsertforeachID.EachIDmayactuallybea//keyinthearray,withextraattributestobeplacedinothercolumns.foreach($idsas$key=>$value){$records[]=$this->attacher($key,$value,$attributes,$timed);}//getrecordsbyidandotherrelationcolumnsreturn$records;}//returnthisrecords/***Createafullp_w_uploadrecordpayload.**@paramint$key*@parammixed$value*@paramarray$attributes*@parambool$timed*@returnarray*/protectedfunctionattacher($key,$value,$attributes,$timed){//Createafullp_w_uploadrecordpayloadlist($id,$extra)=$this->getAttachId($key,$value,$attributes);//listmanyreturn//Tocreatethep_w_uploadrecords,wewillsimplyspinthroughtheIDsgiven//andcreateanewrecordtoinsertforeachID.EachIDmayactuallybea//keyinthearray,withextraattributestobeplacedinothercolumns.$record=$this->createAttachRecord($id,$timed);//idisakeyabouteverythingreturnarray_merge($record,$extra);}//returnthisarray_merge./***GettheattachrecordIDandextraattributes.**@parammixed$key*@parammixed$value*@paramarray$attributes*@returnarray*/protectedfunctiongetAttachId($key,$value,array$attributes){//GettheattachrecordIDandextraattributes.if(is_array($value)){return[$key,array_merge($value,$attributes)];}//astrangethingreturn[$value,$attributes];}//returnthisdefault/***Createanewpivotp_w_uploadrecord.**@paramint$id*@parambool$timed*@returnarray*/protectedfunctioncreateAttachRecord($id,$timed){//Createanewpivotp_w_uploadrecord$record[$this->foreignKey]=$this->parent->getKey();//recordthekey$record[$this->otherKey]=$id;//recordtheotherkey//Iftherecordneedstohavecreationandupdatetimestamps,wewillmake//thembycallingtheparentmodel's"freshTimestamp"methodwhichwill//provideuswithafreshtimestampinthismodel'spreferredformat.if($timed){$record=$this->setTimestampsOnAttach($record);}//ifyouneedtoupdatethistimestamps,justuseparentsmethodreturn$record;}//returnrecord/***Setthecreationandupdatetimestampsonanattachrecord.**@paramarray$record*@parambool$exists*@returnarray*/protectedfunctionsetTimestampsOnAttach(array$record,$exists=false){//thisfunctionjusttrytousefathermethodtosetabouttimestamps$fresh=$this->parent->freshTimestamp();//getthisfunctionreturnif(!$exists&&$this->hasPivotColumn($this->createdAt())){$record[$this->createdAt()]=$fresh;}//checksomeconditionif($this->hasPivotColumn($this->updatedAt())){$record[$this->updatedAt()]=$fresh;}//okreturn$record;}//returnthisrecord/***Detachmodelsfromtherelationship.**@paramint|array$ids*@parambool$touch*@returnint*/publicfunctiondetach($ids=[],$touch=true){//detachmodelsfromtherelationshipif($idsinstanceofModel){$ids=(array)$ids->getKey();//ids=(array)->ids->getKey}//idsinstanceofModel$query=$this->newPivotQuery();//getanewquery//IfassociatedIDswerepassedtothemethodwewillonlydeletethose//associations,otherwisealloftheassociationtieswillbebroken.//We'llreturnthenumbersofaffectedrowswhenwedothedeletes.$ids=(array)$ids;//firsttosettheidsif(count($ids)>0){$query->whereIn($this->otherKey,(array)$ids);}//countthequery//Oncewehavealloftheconditionssetonthestatement,weareready//torunthedeleteonthepivottable.Then,ifthetouchparameter//istrue,wewillgoaheadandtouchallrelatedmodelstosync.$results=$query->delete();//Oncewehavealloftheconditionsonthestatement//arereadytorunthedeleteonthepivottable.if($touch){$this->touchIfTouching();}return$results;}//justreturnthisresults/***Ifwe'retouchingtheparentmodel,touch.**@returnvoid*/publicfunctiontouchIfTouching(){if($this->touchingParent()){$this->getParent()->touch();}if($this->getParent()->touches($this->relationName)){$this->touch();}}//Ifwe'retouchingtheparentmodel,touch./***Determineifweshouldtouchtheparentonsync.**@returnbool*/protectedfunctiontouchingParent(){return$this->getRelated()->touches($this->guessInverseRelation());}//Determineifweshouldtouchtheparentonsync./***Attempttoguessthenameoftheinverseoftherelation.**@returnstring*/protectedfunctionguessInverseRelation(){returnStr::camel(Str::plural(class_basename($this->getParent())));}//Attempttoguessthenameoftheinverseoftherelation/***Createanewquerybuilderforthepivottable.**@return\Illuminate\Database\Query\Builder*/protectedfunctionnewPivotQuery(){//Createanewquerybuilderforthepivottable$query=$this->newPivotStatement();foreach($this->pivotWheresas$whereArgs){call_user_func_array([$query,'where'],$whereArgs);}return$query->where($this->foreignKey,$this->parent->getKey());}//justawrapfunction/***Getanewplainquerybuilderforthepivottable.**@return\Illuminate\Database\Query\Builder*/publicfunctionnewPivotStatement(){return$this->query->getQuery()->newQuery()->from($this->table);}//Getanewplainquerybuilderforthepivottable/***Getanewpivotstatementforagiven"other"ID.**@parammixed$id*@return\Illuminate\Database\Query\Builder*/publicfunctionnewPivotStatementForId($id){return$this->newPivotQuery()->where($this->otherKey,$id);}//Getanewpivotstatementforagiven"other"ID./***Createanewpivotmodelinstance.**@paramarray$attributes*@parambool$exists*@return\Illuminate\Database\Eloquent\Relations\Pivot*/publicfunctionnewPivot(array$attributes=[],$exists=false){$pivot=$this->related->newPivot($this->parent,$attributes,$this->table,$exists);return$pivot->setPivotKeys($this->foreignKey,$this->otherKey);}//Createanewpivotmodelinstance.//returnsetPivotKeys/***Createanewexistingpivotmodelinstance.**@paramarray$attributes*@return\Illuminate\Database\Eloquent\Relations\Pivot*/publicfunctionnewExistingPivot(array$attributes=[]){return$this->newPivot($attributes,true);}//Createanewexistingpivotmodelinstance./***Setthecolumnsonthepivottabletoretrieve.**@paramarray|mixed$columns*@return$this*/publicfunctionwithPivot($columns){$columns=is_array($columns)?$columns:func_get_args();//setthiscolumns.$this->pivotColumns=array_merge($this->pivotColumns,$columns);//pivotarray_mergereturn$this;}//Setthecolumnsonthepivottabletoretrieve./***Specifythatthepivottablehascreationandupdatetimestamps.**@parammixed$createdAt*@parammixed$updatedAt*@return\Illuminate\Database\Eloquent\Relations\BelongsToMany*/publicfunctionwithTimestamps($createdAt=null,$updatedAt=null){$this->pivotCreatedAt=$createdAt;//setuser$this->pivotUpdatedAt=$updatedAt;//setuserreturn$this->withPivot($this->createdAt(),$this->updatedAt());}//Specifythatthepivottablehascreationandupdatetimestamps/***Getthenameofthe"createdat"column.**@returnstring*/publicfunctioncreatedAt(){return$this->pivotCreatedAt?:$this->parent->getCreatedAtColumn();}//Getthenameofthe"createdat"column/***Getthenameofthe"updatedat"column.**@returnstring*/publicfunctionupdatedAt(){return$this->pivotUpdatedAt?:$this->parent->getUpdatedAtColumn();}//pivot/***Gettherelatedmodel'supdatedatcolumnname.**@returnstring*/publicfunctiongetRelatedFreshUpdate(){return[$this->related->getUpdatedAtColumn()=>$this->related->freshTimestamp()];}//justreturn/***Getthekeyforcomparingagainsttheparentkeyin"has"query.**@returnstring*/publicfunctiongetHasCompareKey(){return$this->getForeignKey();}//return/***Getthefullyqualifiedforeignkeyfortherelation.**@returnstring*/publicfunctiongetForeignKey(){return$this->table.'.'.$this->foreignKey;}//return/***Getthefullyqualified"otherkey"fortherelation.**@returnstring*/publicfunctiongetOtherKey(){return$this->table.'.'.$this->otherKey;}//return/***Gettheintermediatetablefortherelationship.**@returnstring*/publicfunctiongetTable(){return$this->table;}//return/***Gettherelationshipnamefortherelationship.**@returnstring*/publicfunctiongetRelationName(){return$this->relationName;}//return}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。