本文介绍了在Laravel中,有没有一种方法可以确定是否创建了"firstOrCreate"或是否找到了该行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Laravel中,有没有一种方法可以区分firstOrCreate
创建行和查找行是否存在?
In Laravel, is there a way to differentiate between firstOrCreate
creating the row and if finding out the row exists from before?
还是我必须先手动执行get()
,然后创建行?
Or will I have to manually do a get()
first, and then create the row?
推荐答案
如果在当前生命周期中创建了模型,则模型的wasRecentlyCreated
属性将设置为true
.否则,该属性将设置为false
.
If you created the model in the current lifecycle, then the model's wasRecentlyCreated
attribute will be set to true
. Otherwise, that attribute will be set to false
.
换句话说,假设您有一个使用电子邮件bob@example
的用户.
In other words, lets say you have a user with the email, bob@example
.
$user = User::firstOrCreate(['email' => '[email protected]']);
// the below will dump out false because this entry already existed
var_dump($user->wasRecentlyCreated);
现在,可以说[email protected]
不存在.
$user2 = User::firstOrCreate(['email' => '[email protected]']);
// the below will dump out true because this user was created
// in the current request lifecycle
var_dump($user2->wasRecentlyCreated);
这篇关于在Laravel中,有没有一种方法可以确定是否创建了"firstOrCreate"或是否找到了该行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!