Last active
June 17, 2023 00:33
-
-
Save InToSSH/ba4cb4d196229df729bdb3568758883c to your computer and use it in GitHub Desktop.
Laravel Eloquent - Order By Relation macro
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 | |
Builder::macro('orderByRelation', function(string $searchColumn, string $dir) { | |
list($relation, $column) = explode('.', $searchColumn); | |
$relation_table = $this->getRelation($relation)->getModel()->getTable(); | |
$relation_foreign_key = $this->getRelation($relation)->getForeignKeyName(); | |
$query_table = $this->getModel()->getTable(); | |
$this->select($query_table . '.*') | |
->join($relation_table, $query_table . '.' . $relation_foreign_key, '=', $relation_table . '.id') | |
->orderBy($relation_table . '.' . $column, $dir); | |
return $this; | |
}); |
Hi, This might help you.
$users = User::get()->sortBy(function($query){
return $query->role->name;
})->all();
$users = User::with(['role' => function ($q) {
$q->orderBy('name', 'desc');
}])->get();
$users = User::select('*')
->orderBy(Role::select('name')
->whereColumn('roles.id', 'users.role_id')
);
You should return $this
at the end so you could chain your query together.
For example: you can call ->get()
directly on the orderByRelation (orderByRelation('relation.column')->get()
)
You should
return $this
at the end so you could chain your query together. For example: you can call->get()
directly on the orderByRelation (orderByRelation('relation.column')->get()
)
Good catch, forgot to include that. Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This way we can keep that ->orderByRelation at the end of a model's filtering and decide. but you know, you're right, there's no need here. thanks man, so precious