Sorting by associated model criteria Hi there,
I cannot find a way to apply the orderBy method to a query, using an associated model criteria. Basically I would like to be able to write something like :
->orderBy('user.email', 'asc');
but this does not work. What would be the correct syntax to do so then?
== CONTROLLER ==
$partners = Partner::where('partners.id', '>', 1)
->whereHas('user', function ( $query ) {
$query->where('active', 1);
});
== MODEL ==
class Partner extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
What are you meaning by associated? You want to first order by user and then email? Then apply orderBy 2 times:
>orderBy('user', 'asc')->orderBy('email', 'asc');
Or do you want to order by a sub query?
I think you are about to create a very heavy query, so maybe tell more what you want and more examples, I think it can be achieved more optimal.
No, I want to order alphabetically by the email of the user, User being an associated model to Partner.
You can't order by a relationship's without joining the table.
I think you'd need to use the raw DB Class,
DB::raw('select, join, stuff,order');
Regards
-Darkninja462
Ok, thanks. That is what I thought. Unfortunately, as I am working with very large databases I cannot use a raw query.
I really don't understand why there is no Eloquent syntax for sorting a model query over an associated-model criteria. This is for me just unbelievable ...
as I am working with very large databases I cannot use a raw query.
Why can't you use raw sql queries on your database ????? Of course you can use sql queries on your database.
Eloquent never joins anything, so you cant do something needing a join.
Just add a join to your query. Of course it works on Eloquent!
Partner::join(...)->orderBy ('users.email')->get ()
Choose the right join to use, fill the join and cascade all your clauses in this query.
Once you do this, you can do clauses using your related model column.
I can't give more details now because I'm outdoor on a mobile! :(
$partners = Partner::join('users', 'partners.user_id', '=', 'users.id')->orderBy('users.email')->get();
Please sign in or create an account to participate in this conversation.