Last active
September 11, 2017 06:17
-
-
Save mindc/8d23ef165ad412db976a86239ba9609b to your computer and use it in GitHub Desktop.
Laravel QueryBuilder and augmented orderBy - order through relations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Database\Eloquent\Relations\HasOneOrMany; | |
use Illuminate\Database\Eloquent\Relations\BelongsTo; | |
trait OrderThroughRelationTrait { | |
/** | |
* Add an "order by" clause to the query and handles relations if specified. | |
* | |
* Supported relations: hasOne, hasMany, belongsTo | |
* | |
* Examples: | |
* Store::orderThroughRelation('name')->get() //same as Store::orderBy('name')->get() | |
* Store::orderThroughRelation('categories.name')->get() | |
* Store::orderThroughRelation('categories.subcategories.name')->get() | |
* Store::orderThroughRelation('categories.subcategories.products.name')->get() | |
* | |
* @param Illuminate\Database\Eloquent\Builder $query | |
* @param string $column | |
* @param string $direction | |
* @return $query | |
*/ | |
public function scopeOrderThroughRelation( $query, $column, $direction = 'asc' ) { | |
if ( $column ) { | |
if ( strpos( $column,'.') !== false ) { | |
$relation_names = explode( '.', $column ); | |
$column = array_pop( $relation_names ); | |
array_reduce( $relation_names, function( $model, $relation_name ) use ($query, &$relation) { | |
$relation = $model->{ $relation_name }(); | |
if ( $relation instanceof HasOneOrMany ) { | |
$query->join( | |
$relation->getModel()->getTable(), | |
$relation->getQualifiedParentKeyName(), | |
'=', | |
$relation->getExistenceCompareKey() ); | |
} else if ( $relation instanceof BelongsTo) { | |
$query->join( | |
$relation->getModel()->getTable(), | |
$relation->getQualifiedOwnerKeyName(), | |
'=', | |
$relation->getQualifiedForeignKey() ); | |
} else { | |
throw new \Error(get_class($relation)); | |
} | |
return $relation->getModel(); | |
}, $query->getModel() ); | |
$query->orderBy( $relation->getModel()->getTable() . '.' . $column, $direction); | |
} else { | |
$query->orderBy( $column, $direction ); | |
} | |
} | |
return $query; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment