Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

php - 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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
    }])->get();
    

    You can inject the parameter to query function by use($param) method, that allows you to use dynemic query value at runtime.

  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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...