saimiris's avatar

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'); } }

0 likes
8 replies
EmilMoe's avatar

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.

saimiris's avatar

No, I want to order alphabetically by the email of the user, User being an associated model to Partner.

pmall's avatar

You can't order by a relationship's without joining the table.

darkninja462's avatar

I think you'd need to use the raw DB Class,

DB::raw('select, join, stuff,order');

Regards -Darkninja462

saimiris's avatar

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 ...

pmall's avatar

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.

EliasSoares's avatar

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! :(

willvincent's avatar
$partners = Partner::join('users', 'partners.user_id', '=', 'users.id')->orderBy('users.email')->get();

Please or to participate in this conversation.