Query relationship Eloquent

I have News model, and News has many comments, so I did this in News model:

public function comments(){
    $this->hasMany('Comment', 'news_id');
}

But I also have field trashed in comments table, and I only want to select comments that are not trashed. So trashed <> 1. So I wonder is there a way to do something like this:

$news = News::find(123);
$news->comments->where('trashed', '<>', 1); //some sort of pseudo-code

Is there a way to use above method or should I just write something like this:

$comments = Comment::where('trashed', '<>', 1)
    ->where('news_id', '=', $news->id)
    ->get();

Answers


Any of these should work for you, pick the one you like the most:

  1. Eager-loading.

    $comments = News::find(123)->with('comments', function ($query) {
        $query->where('trashed', '<>', 1);
    });
    
  2. Lazy-loading

    $news = News::find(123);
    $comments = $news->comments()->where('trashed', '<>', 1)->get();
    

I couldn't help but notice, though, that what you're probably trying to do is handle soft deleting, and that Laravel has built-in functionality to help you with that: http://laravel.com/docs/eloquent#soft-deleting


rmobis's answer was what I needed, but it throws an error in current Laravel 5. You have to use it as an associatve array now:

$comments = News::find(123)->with(
    ['comments' => function ($query) {$query->where('trashed', '<>', 1);}]
);

Took me some time to figure it out, hope this will help others.

Read more in Laravel's Docs (5.6): https://laravel.com/docs/5.6/eloquent-relationships#querying-relations


You can do simply in your eloquent model file. do like this :

public function comments_with_deleted()
{
    return $this->belongsTo('Comments', 'id')->where('deleted', 1);
}

public function comments()
{
    return $this->belongsTo('Comments', 'id');
}

call like this :

// for show comments with deleted
$comments = News::find(123)->with('comments_with_deleted');

// for show comments without deleted
$comments = News::find(123)->with('comments');

Need Your Help

Undefined reference to 'dlsym'

c++ gcc compiler-errors ubuntu-13.10

I have seen a lot of similar posts, but tried every trick in the book and am still struggling. Everything was working fine, but after installing/removing wireshark with some components/disselectors...

Webkit backface visibility not working

css css3 webkit

I'm building a simple example to flip a card using the -webkit-transform: rotateY property.