I have a query which joins one table with another one in a one to one relation. How can I sort the result by a column in the joining relation
$relation = ModelObject::where('status', '=', 1)
->with('related_table')
->get()
I need to sort this with a column(Eg: name) of related_table
. How to do this in eloquent.
You can use orderBy
$relation = ModelObject::where('status', '=', 1)
->with('related_table')
->orderBy('related_table.field') //field name is the name of the field on the basis of which you want to sort
->get();
As per the laravel docs you can add additional constraints like this,
Constraining Eager Loads
Sometimes you may wish to eager load a relationship, but also specify additional query constraints for the eager loading query. Here's an example:
$users = App\User::with(['posts' => function ($query) {
$query->where('title', 'like', '%first%');
}])->get();
Finally your code should be something like this,
$relation = ModelObject::where('status', '=', 1)
->with(['related_table' => function($query) {
$query->orderBy('field', 'asc|desc');
}])
->get()
you may use this
$categories = Category::select(DB::raw('categories.*, count(*) as
`aggregate`'))
->join('pictures', 'categories.id', '=', 'pictures.category_id')
->groupBy('category_id')
->orderBy('aggregate', 'desc');