Home > Enterprise >  How to sort the result of this query
How to sort the result of this query

Time:08-03

I have theses 2 models : Bettor and User.

These models are linked between them like that :

For the Bettor :

public function user()
{
    return $this->belongsTo(User::class);
}

For the User :

public function bettors()
{
    return $this->hasMany(Bettor::class);
}

I have this query :

return Bettor::where('bet_id', $bet->id)
    ->with(['user' => function ($query) {
        $query->orderBy('email');
    }])
    ->get();

The result does not sort the users with their emails. But when I read the documentation here, it is possible to do that :

https://laravel.com/docs/9.x/eloquent-relationships#constraining-eager-loads

I could sort the collection after the query, but of course it would not be the correct method.

So where is my mistake ?

CodePudding user response:

There are 2 things.

1- If you want to order your relationship then it's working fine. The relationship data you're getting is actually getting sorted.

2- If you want to get the Bettor sorted on the basis of user's email then:

Bettors::query()->where('bet_id', $bet->id)->with('user')->orderBy(User::select('email)->whereColumn('users.id', 'bettors.user_id'))->get();

This will return back the results based on relationship's column sorting. What this query is doing is that orderBy can take in a sub-query so we are using a sub-query and selecting the email column.

I Hope this is the answer you're looking for.

CodePudding user response:

Bettor::with('user')->where('bet_id', $bet->id)->get()->sortByDesc('user.email');

This will sort the results of the query after eager loading using collection methods and not by a MySQL ORDER BY.

  • Related