I posted this same message on the Laracasts forums but didn't get any replies, thought I would give it a shot here.
Is anyone else have issues with eager loading constraints not working in Laravel 5? I'm trying to do exactly what the documentation is doing:
http://laravel.com/docs/4.2/eloquent#eager-loading
$users = User::with(array('posts' => function($query)
{
$query->orderBy('created_at', 'desc');
}))->get();
Which is, changing the order of a result based on a value of an eager loaded child, however it's just not working for me. The order never changes. I literally even copied the exact code from the documentation (just altered the field names to match my schema), and it still didn't work.
Wondering if I'm just doing something wrong or if it's broken in L5. Anyone else have issues with it?
Your assumption is wrong. Eager loading never affected base query in any way, order
clause you set there, affects only the related table query, which is posts
.
To do what you want you need join
.
@jarektkaczyk Thank you for the point in the right direction!
Correct me if I'm wrong though, but isn't using the with() method essentially doing a join within the eloquent fluent syntax? Or is that incorrect? I don't see anything in the Eloquent documentation (http://laravel.com/docs/4.2/eloquent) about a join() method.
So to follow up here, I was basically able to get this working with a join along these lines:
$users = User::join('posts', function($join)
{
$join->on('users.id', '=', 'posts.user_id');
}))->orderBy('posts.created_at', 'desc')->get();
However, it looks like once you do a join query on an eloquent model, you can no longer do things like use the "with" method elsewhere. As in, in my views, I can no longer access $user->posts->property_name directly, because it's merged the 2 data results together. Is there anyway to utilize joins to for the orderBy but also keep the "with" functionality?
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community