[李景山php]每天laravel-20161130|BelongsToMany.php-2
/***Getthepivotattributesfromamodel.**@param\Illuminate\Database\Eloquent\Model$model*@returnarray*/protectedfunctioncleanPivotAttributes(Model$model){//Getthepivotattributesfromamodel$values=[];//setthestorevaluesforeach($model->getAttributes()as$key=>$value){//loopattributes//Togetthepivotsattributeswewilljusttakeanyoftheattributeswhich//beginwith"pivot_"andaddthosetothisarrays,aswellasunsetting//themfromtheparent'smodelssincetheyexistinadifferenttable.if(strpos($key,'pivot_')===0){//ifhasthispivot_*key,$values[substr($key,6)]=$value;//dumpthevalueintargetarrayunset($model->$key);//unsetthesource}}return$values;//returnthisresult}/***Setthebaseconstraintsontherelationquery.**@returnvoid*/publicfunctionaddConstraints(){//Setthebaseconstraintsontherelationquery.$this->setJoin();//firsttosetJoin//setConstraintsif(static::$constraints){//ifhasthisflagthensetWhere$this->setWhere();}}/***Addtheconstraintsforarelationshipquery.**@param\Illuminate\Database\Eloquent\Builder$query*@param\Illuminate\Database\Eloquent\Builder$parent*@paramarray|mixed$columns*@return\Illuminate\Database\Eloquent\Builder*/publicfunctiongetRelationQuery(Builder$query,Builder$parent,$columns=['*']){//Addtheconstraintsforarelationshipquery.if($parent->getQuery()->from==$query->getQuery()->from){return$this->getRelationQueryForSelfJoin($query,$parent,$columns);}//ifsametheparentwiththisclassself//returnthegetRelationQueryForSelfJoin$this->setJoin($query);//setJoinreturnparent::getRelationQuery($query,$parent,$columns);//justRelationQuery}//defaultuseparentsfunction/***Addtheconstraintsforarelationshipqueryonthesametable.**@param\Illuminate\Database\Eloquent\Builder$query*@param\Illuminate\Database\Eloquent\Builder$parent*@paramarray|mixed$columns*@return\Illuminate\Database\Eloquent\Builder*/publicfunctiongetRelationQueryForSelfJoin(Builder$query,Builder$parent,$columns=['*']){//Addtheconstraintsforarelationshipqueryonthesametable.$query->select($columns);//firstsetselect$query->from($this->related->getTable().'as'.$hash=$this->getRelationCountHash());//setfrom$this->related->setTable($hash);//settable$this->setJoin($query);//setJoinreturnparent::getRelationQuery($query,$parent,$columns);}//thenusetheGetRelationQuery/***Getarelationshipjointablehash.**@returnstring*/publicfunctiongetRelationCountHash(){return'self_'.md5(microtime(true));}//getthehashkey/***Settheselectclausefortherelationquery.**@paramarray$columns*@return\Illuminate\Database\Eloquent\Relations\BelongsToMany*/protectedfunctiongetSelectColumns(array$columns=['*']){//Settheselectclausefortherelationquery.//clauselikeconstraintslikethishtmltaglist,yeahif($columns==['*']){$columns=[$this->related->getTable().'.*'];}//ifthis*options,sowewillgetalltablereturnarray_merge($columns,$this->getAliasedPivotColumns());}//returnthiscolumnswiththeorigincolumnsoptions//eventhealias,soitiseveryimport/***Getthepivotcolumnsfortherelation.**@returnarray*/protectedfunctiongetAliasedPivotColumns(){//Getthepivotcolumnsfortherelation$defaults=[$this->foreignKey,$this->otherKey];//firstwesetthedefaults//Weneedtoaliasallofthepivotcolumnswiththe"pivot_"prefixsowe//caneasilyextractthemoutofthemodelsandputthemintothepivot//relationshipswhentheyareretrievedandhydratedintothemodels.$columns=[];//retrievedlikecover;//columns:beprepareforthecolumnsforeach(array_merge($defaults,$this->pivotColumns)as$column){//loopsourceascolumn$columns[]=$this->table.'.'.$column.'aspivot_'.$column;}//setthecolumnsreturnarray_unique($columns);}//returntheuniquekeyarray/***Determinewhetherthegivencolumnisdefinedasapivotcolumn.**@paramstring$column*@returnbool*/protectedfunctionhasPivotColumn($column){//Determinewhetherthegivencolumnisdefinedasapivotcolumnreturnin_array($column,$this->pivotColumns);}//asystemfunctionbewrapbyapackagefunction/***Setthejoinclausefortherelationquery.**@param\Illuminate\Database\Eloquent\Builder|null$query*@return$this*/protectedfunctionsetJoin($query=null){//Setthejoinclausefortherelationquery$query=$query?:$this->query;//firsttosetthequerysql//Weneedtojointotheintermediatetableontherelatedmodel'sprimary//keycolumnwiththeintermediatetable'sforeignkeyfortherelated//modelinstance.Thenwecansetthe"where"fortheparentmodels.$baseTable=$this->related->getTable();//intermediatelikemiddle//getthebaseTable$key=$baseTable.'.'.$this->related->getKeyName();//setkey$query->join($this->table,$key,'=',$this->getOtherKey());return$this;//returnthisclassquery}/***Setthewhereclausefortherelationquery.**@return$this*/protectedfunctionsetWhere(){//Setthewhereclausefortherelationquery.$foreign=$this->getForeignKey();//firstgettheforegin$this->query->where($foreign,'=',$this->parent->getKey());//setthewheresqlqueryreturn$this;}//returnthequery/***Settheconstraintsforaneagerloadoftherelation.**@paramarray$models*@returnvoid*/publicfunctionaddEagerConstraints(array$models){//addEagerConstraints$this->query->whereIn($this->getForeignKey(),$this->getKeys($models));//wrapthisfunctionwithwhereIn}//Settheconstraintsforaneagerloadoftherelation/***Initializetherelationonasetofmodels.**@paramarray$models*@paramstring$relation*@returnarray*/publicfunctioninitRelation(array$models,$relation){//Initializetherelationonasetofmodelsforeach($modelsas$model){$model->setRelation($relation,$this->related->newCollection());}//loopitandsettheRelationreturn$models;}//returnthismodelsfamily/***Matchtheeagerlyloadedresultstotheirparents.**@paramarray$models*@param\Illuminate\Database\Eloquent\Collection$results*@paramstring$relation*@returnarray*/publicfunctionmatch(array$models,Collection$results,$relation){//Matchtheeagerlyloadedresultstotheirparents$dictionary=$this->buildDictionary($results);//setthedictionarybebuildDictionary//Oncewehaveanarraydictionaryofchildobjectswecaneasilymatchthe//childrenbacktotheirparentusingthedictionaryandthekeysonthe//theparentmodels.Thenwewillreturnthehydratedmodelsbackout.foreach($modelsas$model){//loopallvaluesbythisdictionaryif(isset($dictionary[$key=$model->getKey()])){$collection=$this->related->newCollection($dictionary[$key]);$model->setRelation($relation,$collection);}}return$models;//returnthemodels}/***Buildmodeldictionarykeyedbytherelation'sforeignkey.**@param\Illuminate\Database\Eloquent\Collection$results*@returnarray*/protectedfunctionbuildDictionary(Collection$results){//Buildmodeldictionarykeyedbytherelationforeignkey$foreign=$this->foreignKey;//justuseselfkey//Firstwewillbuildadictionaryofchildmodelskeyedbytheforeignkey//oftherelationsothatwewilleasilyandquicklymatchthemtotheir//parentswithouthavingapossiblyslowinnerloopsforeverymodels.$dictionary=[];//buildadictionaryforeach($resultsas$result){$dictionary[$result->pivot->$foreign][]=$result;}//setthisreturn$dictionary;}//returnthedictionary/***Touchalloftherelatedmodelsfortherelationship.**E.g.:Touchallrolesassociatedwiththisuser.**@returnvoid*/publicfunctiontouch(){//associated:likerelation//touchisaorderinlinuxsystem$key=$this->getRelated()->getKeyName();//settheke$columns=$this->getRelatedFreshUpdate();//setorevengetthecolumns//IfweactuallyhaveIDsfortherelation,wewillrunthequerytoupdateall//therelatedmodel'stimestamps,tomakesuretheseallreflectthechanges//totheparentmodels.Thiswillhelpuskeepanycachingsynceduphere.$ids=$this->getRelatedIds();//getids//cachingsyncedif(count($ids)>0){$this->getRelated()->newQuery()->whereIn($key,$ids)->update($columns);}//countthegetRelated}/***GetalloftheIDsfortherelatedmodels.**@return\Illuminate\Support\Collection*/publicfunctiongetRelatedIds(){//GetalloftheIDsfortherelatedmodels$related=$this->getRelated();//related$fullKey=$related->getQualifiedKeyName();//setfullkeyreturn$this->getQuery()->select($fullKey)->pluck($related->getKeyName());}//getQuery
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。