查询关系雄辩

2022-08-30 14:10:29

我有模型,并且有很多评论,所以我在模型中做了这个:NewsNewsNews

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

但我在表中也有字段,我只想选择没有被丢弃的注释。所以。所以我想知道有没有办法做这样的事情:trashedcommentstrashed <> 1

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

有没有办法使用上述方法,或者我应该这样写:

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

答案 1

这些中的任何一个都应该适合您,选择您最喜欢的一个:

  1. 急于加载。

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

    您可以通过方法将参数注入查询函数,这允许您在运行时使用动态查询值。use($param)

  2. 延迟加载

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

不过,我不禁注意到,你可能要做的是处理软删除,而Laravel有内置的功能来帮助你:http://laravel.com/docs/eloquent#soft-deleting


答案 2

您可以在雄辩的模型文件中简单地完成操作。做这个 :

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

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

像这样调用:

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

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

推荐