首先或创建 [英] First Or Create

查看:11
本文介绍了首先或创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道使用:

User::firstOrCreate(array('name' => $input['name'], 'email' => $input['email'], 'password' => $input['password']));

先检查用户是否存在,如果不存在则创建,但是如何检查呢?它是否检查提供的所有参数,或者有没有办法指定特定的参数,例如我可以检查电子邮件地址是否存在,而不是姓名 - 因为两个用户可能具有相同的姓名,但他们的电子邮件地址需要是唯一的.

Checks whether the user exists first, if not it creates it, but how does it check? Does it check on all the params provided or is there a way to specifiy a specific param, e.g. can I just check that the email address exists, and not the name - as two users may have the same name but their email address needs to be unique.

推荐答案

firstOrCreate()找到匹配项之前检查所有要存在的参数.如果并非所有参数都匹配,则将创建模型的新实例.

firstOrCreate() checks for all the arguments to be present before it finds a match. If not all arguments match, then a new instance of the model will be created.

如果您只想检查特定字段,请使用 firstOrCreate(['field_name' => 'value']) 数组中只有一项.这将返回匹配的第一个项目,如果没有找到匹配项,则创建一个新项目.

If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) with only one item in the array. This will return the first item that matches, or create a new one if not matches are found.

firstOrCreate()firstOrNew() 的区别:

    如果没有找到匹配项,
  • firstOrCreate() 将自动在数据库中创建一个新条目.否则它会给你匹配的项目.
  • firstOrNew() 会给你一个新的模型实例,如果发现不匹配,只会在你明确这样做时保存到数据库中(调用 save() 在模型上).否则它会给你匹配的项目.
  • firstOrCreate() will automatically create a new entry in the database if there is not match found. Otherwise it will give you the matched item.
  • firstOrNew() will give you a new model instance to work with if not match was found, but will only be saved to the database when you explicitly do so (calling save() on the model). Otherwise it will give you the matched item.

选择其中之一取决于您想要做什么.如果您想在第一次保存之前修改模型实例(例如设置 name 或一些必填字段),您应该使用 firstOrNew().如果你可以直接使用参数在数据库中立即创建一个新的模型实例而不修改它,你可以使用 firstOrCreate().

Choosing between one or the other depends on what you want to do. If you want to modify the model instance before it is saved for the first time (e.g. setting a name or some mandatory field), you should use firstOrNew(). If you can just use the arguments to immediately create a new model instance in the database without modifying it, you can use firstOrCreate().

这篇关于首先或创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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