find()、findOrFail()、first()、firstOrFail()、get()、list()、toArray()有什么区别 [英] What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

查看:40
本文介绍了find()、findOrFail()、first()、firstOrFail()、get()、list()、toArray()有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些方法有什么区别:

  1. find()
  2. findOrFail()
  3. first()
  4. firstOrFail()
  5. get()
  6. list()
  7. toArray()

我一直在使用它们,每个都给出了不同的结果,有时我需要在 get() 的末尾添加 toArray() 因为我的函数是期待一个数组.其他方法不会也生成数组吗?

I've been using them and each one gives a different result and sometimes I need to add toArray() at the end of get() because my function is expecting an array. Won't the other methods produce arrays as well?

推荐答案

  1. find($id) 接受一个 id 并返回一个模型.如果不存在匹配的模型,则返回null.

findOrFail($id) 接受一个 id 并返回一个模型.如果不存在匹配的模型,则会抛出错误1.

first() 返回在数据库中找到的第一条记录.如果不存在匹配的模型,则返回null.

firstOrFail() 返回在数据库中找到的第一条记录.如果不存在匹配的模型,则会抛出错误1.

get() 返回与查询匹配的模型集合.

get() returns a collection of models matching the query.

pluck($column) 仅返回给定列中值的集合.在以前的 Laravel 版本中,此方法称为 lists.

toArray() 将模型/集合转换为一个简单的 PHP 数组.

toArray() converts the model/collection into a simple PHP array.

<小时>

注意: 一个集合是一个增强的数组.它的功能类似于数组,但具有许多附加功能,正如您在 文档.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

不幸的是,PHP 不允许您在任何可以使用数组的地方使用集合对象.例如,在 foreach 循环中使用集合是可以的,将它传递给 array_map 则不行.类似地,如果您将参数类型提示为 array,PHP 不会让您向它传递集合.从 PHP 7.1 开始,有 iterable 类型提示,可用于接受数组和集合.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

如果您想从集合中获取普通数组,请调用其all() 方法.

If you ever want to get a plain array from a collection, call its all() method.

1 findOrFailfirstOrFail 方法抛出的错误是一个 ModelNotFoundException.如果你自己没有捕捉到这个异常,Laravel 会以 404 响应,这是您大多数时候想要的.

1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

这篇关于find()、findOrFail()、first()、firstOrFail()、get()、list()、toArray()有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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