1

This is my model

  • User
  • Role

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.

1
  • Without a join it's not possible (AFAIK). Commented Oct 7, 2017 at 14:22

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Usually it's better to explain a solution instead of just posting some rows of anonymous code. You can read How do I write a good answer, and also Explaining entirely code-based answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.