先创或创建 [英] First Or Create

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

问题描述

我知道使用:

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

检查用户是否存在第一个,如果不是它创建它,但是如何检查?它检查所提供的所有参数,还是有一种方式来指定特定的参数,例如我可以检查电子邮件地址是否存在,而不是名称,因为两个用户可能具有相同的名称,但电子邮件地址需要是唯一的。

解决方案

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



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



firstOrCreate() firstOrNew()




  • 如果找不到匹配项,firstOrCreate()将自动在数据库中创建一个新条目。否则会给你匹配的项目。

  • firstOrNew()将给你一个新的模型实例,如果不匹配发现,但只有当您明确地这样做(仅在模型上调用 save()才会保存到数据库)。否则它会给你匹配的项目。



选择一个或另一个取决于你想要做什么。如果要在首次保存之前修改模型实例(例如设置名称或某些必填字段),则应使用 firstOrNew ()。如果您只需使用参数即可在数据库中立即创建新的模型实例,而不对其进行修改,则可以使用 firstOrCreate()


I know using:

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() 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.

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.

The difference between firstOrCreate() and firstOrNew():

  • 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.

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