user3844579
user3844579

Reputation: 505

Laravel order by relationship

I have a query:

 $users =  User::byRole()->inCompany()
        ->with([
            'role'     => function ($q) {
                $q->select('id', 'title')->orderBy('title','DESC');
            },
            'company'  => function ($q) {
                $q->select('id', 'company_name');
            },
            'projects' => function ($q) {
                $q->select('id', 'name');
            },
        ])->select([
            'email',
            'id',
            'company_id',
        ])->paginate();

The issue is that it wont order by the role title.

What am i doing wrong?

Thank you

Upvotes: 0

Views: 1635

Answers (2)

webdevtr
webdevtr

Reputation: 480

You also use join like this,

->join('roles','roles.id','user.role_id')
...
...
->orderBy('roles.title', 'DESC')

I hope this will help you

Upvotes: 1

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25936

You can use a modified withCount():

$users =  User::byRole()->inCompany()
    ->with([
        'role'     => function ($q) {
            $q->select('id', 'title');
        },
        'company'  => function ($q) {
            $q->select('id', 'company_name');
        },
        'projects' => function ($q) {
            $q->select('id', 'name');
        },
    ])->select([
        'email',
        'id',
        'company_id',
    ])->withCount(['role as title' => function ($q) {
        $q->select('title');
    })->orderBy('title', 'DESC')
    ->paginate();

Upvotes: 1

Related Questions