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
.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With