Babak no'doust
Babak no'doust

Reputation: 641

Laravel: Orderby in related table and with

This is my model

and relationship between of those models are many to many.

I want to create query like this:

return User::with('roles')->orderBy('roles.id')->paginate();

I don't want join because I created a base class for every model. I also don't want use orderBy after get because it must load all of my data and after that I should be able to sort and paginate it. So it is not a very good idea.

Upvotes: 1

Views: 611

Answers (2)

Nitish Kumar
Nitish Kumar

Reputation: 6276

You can try something like this:

return User::with(['roles'  => function ($query) {
        $query->orderBy('id', 'desc');
    }])->paginate();

But this will only order the eager loading attributes, but if you are interested to use join you can have something like this:

return User::with('roles')
    ->join('roles', 'user.id', '=', 'roles.user_id')
    ->orderBy('roles.id', 'desc')
    ->paginate();

In this you can easily use paginate which is your main concern.

Hope this helps.

Upvotes: 1

Silvio Hanky
Silvio Hanky

Reputation: 61

User::where('role_id','!=','0')->orderBy('role_id','DESC')->paginate(10);

Upvotes: 0

Related Questions