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

I found a solution for my question , it's simply to concat the "with:

$posts = Post::with('user') ->with(array('comments.user'=>function($query){ $query->where('created_at', '=', 1); })) ->with('tags') ->where('travel_area_id','=',$area->id) ->take($this->numOfPostsInAreaPageLoad) ->orderBy('created_at', 'DESC') ->get();

but now I would like to have an eager load constraint on "comments.user" more specifically on the comments, and not on the user, any idea how, because the current where inflects the query for the user of the comment.

Last updated 1 year ago.
0

AMAZING!!!!

found the solution, you should nest each one of the eager loads inside

$posts = Post::with('user')
     ->with(array('comments'=>function($query){
         $query->where('user_id', '=', 3);
         $query->with('user');
     }))
     ->with('tags')
     ->where('travel_area_id','=',$area->id)
     ->take($this->numOfPostsInAreaPageLoad)
     ->orderBy('created_at', 'DESC')
     ->get();
Last updated 1 year ago.
0

Hey bud, glad you could figure it out.

I don't mean to hijack your thread, but could you take a look at the post I made a couple hours ago because I think I'm struggling with a similar issue as this, but can't make sense of your answer right now.

http://laravel.io/forum/02-10-2014-creating-a-filter-for-resul...

Last updated 1 year ago.
0

Alternative method using dot notation:

https://laracasts.com/discuss/channels/general-discussion/nest...

When testing:

$query->with([
    'children' => function ($q) {
        $q->where('someCol', 'someVal'); //constraint on children
    },'children.grandchildren' => function ($q) {
            $q->where('someOtherCol', 'someOtherVal'); //constraint on grandchildren
    }
]);

Use:

dd($result->first()->children->first()->grandchildren->first());

NOT:

dd($result->first()->children()->first()->grandchildren()->first());

Note the parentheses which cause the relationships to be returned as queries instead of dynamic properties. Then first() gets called on a query instead of a collection, returning a fresh database response which doesn't have the specified constraints.

I was tearing my hair out trying to figure out why my where was being skipped until I spotted the extra parentheses.

Last updated 7 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

tzookb tzookb Joined 9 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.