laravel Eloquent\Model::get() 和 all() 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34587457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between Eloquent\Model::get() and all()
提问by David Rodrigues
回答by patricus
User::all()
and User::get()
will do the exact same thing.
User::all()
并且User::get()
会做完全相同的事情。
all()
is a static method on the Eloquent\Model
. All it does is create a new query object and call get()
on it. With all()
, you cannot modify the query performed at all (except you can choose the columns to select by passing them as parameters).
all()
是一个静态方法Eloquent\Model
。它所做的只是创建一个新的查询对象并调用get()
它。使用all()
,您根本无法修改执行的查询(除非您可以通过将它们作为参数传递来选择要选择的列)。
get()
is a method on the Eloquent\Builder
object. If you need to modify the query, such as adding a where clause, then you have to use get()
. For example, User::where('name', 'David')->get();
.
get()
是Eloquent\Builder
对象上的方法。如果您需要修改查询,例如添加 where 子句,那么您必须使用get()
. 例如,User::where('name', 'David')->get();
。
回答by Kenny
To further clarify why this works, it is because there is a magic method in the Model class which will take any static call that is not defined, create an instance, then call the method on the instance for you.
为了进一步澄清为什么会这样,这是因为 Model 类中有一个魔法方法,它会接受任何未定义的静态调用,创建一个实例,然后为您调用实例上的方法。
You can see it in the source code here: https://github.com/laravel/framework/blob/5.6/src/Illuminate/Database/Eloquent/Model.php(line 1580)
您可以在此处的源代码中看到它:https: //github.com/laravel/framework/blob/5.6/src/Illuminate/Database/Eloquent/Model.php(第 1580 行)
This is also explained in this Laracast episode: https://laracasts.com/series/advanced-eloquent/episodes/3(Subscription required)
这在 Laracast 剧集中也有解释:https://laracasts.com/series/advanced-eloquent/episodes/3 (需要订阅)
I too was mystified when I first came across this and couldn't find get()
as a static method. But then I recalled the Laracast episode which helped me connect the dots.
当我第一次遇到这个并且找不到get()
静态方法时,我也很困惑。但后来我想起了帮助我连接点的 Laracast 插曲。