user3189734
user3189734

Reputation: 665

Laravel 4 - list posts collection only with associated comments

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

Answers (2)

Jarek Tkaczyk
Jarek Tkaczyk

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

azngunit81
azngunit81

Reputation: 1604

with('comments') is to eager load

what you need is actually a join on with a where.

Upvotes: 1

Related Questions