查询关系雄辩 [英] Query relationship Eloquent

查看:35
本文介绍了查询关系雄辩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 News 模型,而 News 有很多评论,所以我在 News 模型中做到了:

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

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

但是我在 comments 表中也有 trashed 字段,我只想选择未删除的注释.因此,删除了<>1 .所以我想知道是否有办法做这样的事情:

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();

推荐答案

其中任何一种都可以为您工作,选择最喜欢的一种:

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

  1. 渴望加载.

  1. Eager-loading.

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

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

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

延迟加载

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


不过,我不禁注意到,您可能想做的是处理软删除,而Laravel具有内置功能可以帮助您解决此问题: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆