Support the ongoing development of Laravel.io →
Database Eloquent Architecture
Last updated 1 year ago.
0

Use join because eager loading runs 2nd query, so you'll end up with jobs ordered by whatever you like but it won't affect users order.

Last updated 1 year ago.
0

jarektkaczyk said:

Use join because eager loading runs 2nd query, so you'll end up with jobs ordered by whatever you like but it won't affect users order.

Can you please write the suggested query?

Last updated 1 year ago.
0

In fact I didn't notice you wanted to load jobs for a signle user, my bad! So if that's the case, then you are free to use eager loading / lazy eager loading:

Auth::user()->load(['jobs' => function ($q) { 
   $q->orderBy('job_user.created_at','asc');
}]);
Last updated 1 year ago.
0
Solution

Ok I found a solution myself, It's as simple as this:

Auth::user()->jobs()
            ->orderBy('job_user.created_at', 'desc')
            ->get();
Last updated 1 year ago.
0

Another Solution for this:

Auth::user()->jobs()
               ->orderBy('pivot_created_at', 'desc')
               ->get();

In model, you should define created_at from the pivot with withPivot method

public function jobs()
{
       return $this->belongsToMany('Jobs')->withPivot('created_at');
}
Last updated 8 years ago.
0

ammont said:

Ok I found a solution myself, It's as simple as this:

Auth::user()->jobs()
           ->orderBy('job_user.created_at', 'desc')
           ->get();

Thanks! You saved my late

$saved = Service::findOrFail($request->service_id)->products()->orderBy('product_service.updated_at', 'desc')->first();

That was my issue...

Last updated 7 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

ammont ammont Joined 10 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.