Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4.1 Eloquent - Filtering a relationship collection

I am having problems filtering a relationship using laravel 4.1 hasWhere.

Iteration 1 - Get all posts: Done

$posts = Post::all();

Iteration 2 - Get all posts lazy load comments: Done

$posts = Post::with('comments')->get();

Iteration 3 - Get only posts with comments and lazy load: Done

$posts = Post::with('comments')->has('comments')->get();

Iteration 4 - Get only posts with published comments and lazy load: Broken

$posts = Post::with('comments')
    ->whereHas('comments', function($q) {
        return $q->where('published', '=', 1);
    })
    ->get();

Output of print_r($posts->toArray()) shows output of iteration 3 and 4 as exactly the same. I am unable to filter the relation based on the condition that 'comments.published' = 1.

like image 490
Gravy Avatar asked Nov 01 '22 07:11

Gravy


1 Answers

I have found a solution, however I am uncertain that this is the most elegant solution. As such, I am leaving this open for better suggestions.

    $posts = Post::
        ->whereHas('comments', function($q)
            {
                $q->where('published', '=', 1);
            })
        ->with([
            'comments' => function($q)
            {
                $q->where('published', '=', 1);
            },
            ])->get();

Basically, my solution involves filtering eloquent results, and also filtering lazy loading separately. Is this necessary? Is there a better way of achieving this?

like image 104
Gravy Avatar answered Nov 07 '22 20:11

Gravy