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

问题描述

我发现这些方法背后的概念和含义有点令人困惑,是否有人可以向我解释 haswith 之间的区别是,在示例的上下文中(如果可能)?

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

with() 用于快速加载.这基本上意味着,沿着主模型,Laravel 将预加载您指定的关系.如果您有一组模型并且想要为所有模型加载关系,这将特别有用.因为使用预先加载,您只会运行一个额外的数据库查询,而不是为集合中的每个模型运行一个.

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.

示例:

用户>有许多 >发布

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

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.

示例:

用户>有许多 >发布

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

哪里有

whereHas() 的工作原理与 has() 基本相同,但允许您为要检查的相关模型指定额外的过滤器.

WhereHas

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

示例:

用户>有许多 >发布

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

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

08-03 22:24
查看更多