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

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

问题描述

这些方法之间有什么区别?

What is the difference between these methods:

  1. find()
  2. findOrFail()
  3. first()
  4. firstOrFail()
  5. get()
  6. list()
  7. 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 typehint ,可用于接受数组和集合.

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方法引发的错误是

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天全站免登陆