Reputation: 665
I'm trying to display a list of posts that have NO comments associated with them. In other words, in my one-to-many relationship, if there are children, the post shouldn't display.
Besides doing this with raw query, is there an easy way to do this eloquently?
Model - Post.php
public function comments()
{
return $this->hasMany('Comment');
}
Model - Comment.php
public function post()
{
return $this->belongsTo('Post');
}
Controller - PostController.php
public function unanswered()
{
$posts = Post::with('comments')
->orderBy('created_at', 'desc')
->paginate(5);
return View::make('unanswered')->with('posts',$posts);
}
Upvotes: 0
Views: 109
Reputation: 81167
In order to fetch models that either have, or not, given relation, you need to use has
method.
Depending on what you want to achieve use plain has('relation')
or pass additional parameters:
$posts = Post::has('comments', '<', 1)->get();
Upvotes: 1
Reputation: 1604
with('comments') is to eager load
what you need is actually a join on with a where.
Upvotes: 1