Laravel - 雄辩的“Has”,“With”,“WhereHas” - 他们的意思是什么? [英] Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

查看:184
本文介绍了Laravel - 雄辩的“Has”,“With”,“WhereHas” - 他们的意思是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经发现这些方法的概念和含义有点混乱,有人可以向我解释一下,之间的区别是在一个例子的上下文中(如果可能的话)?

I've found the concept and meaning behind these methods to be a little confusing, is it possible for somebody to explain to me what the difference between has and with is, in the context of an example (if possible)?

推荐答案

使用



with()用于加载。这基本上意味着,沿着主要的模式,Laravel会预先加载你指定的关系。如果您有一个模型集合并且想要加载所有这些模型的关系,这一点尤其有用。因为加载速度很快,您只能为集合中的每个模型运行一个额外的DB查询而不是一个。

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

示例:

用户> hasMany>发布

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}



h2>

has()是基于关系过滤选择模型。所以它与正常的WHERE条件非常相似。如果你只是使用 has('relation'),这意味着你只想得到这个关系中至少有一个相关模型的模型。

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

示例:

用户> hasMany>发布

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection



WhereHas



whereHas()的工作原理与 has(),但允许您指定相关模型的其他过滤器进行检查。

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

示例:

用户> hasMany>发布

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from this year are returned

这篇关于Laravel - 雄辩的“Has”,“With”,“WhereHas” - 他们的意思是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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