在 Laravel 中,有没有办法找出是否创建了 `firstOrCreate` 或者是否找到了该行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36543477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Laravel, is there a way to find out whether `firstOrCreate` created or if it found the row?
提问by Pat
In Laravel, is there a way to differentiate between firstOrCreate
creating the row and if finding out the row exists from before?
在 Laravel 中,有没有办法区分firstOrCreate
创建行和之前是否发现该行存在?
Or will I have to manually do a get()
first, and then create the row?
还是我必须先手动执行get()
,然后再创建行?
回答by Thomas Kim
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
.
如果您在当前生命周期中创建了模型,则模型的wasRecentlyCreated
属性将设置为true
。否则,该属性将设置为false
。
In other words, lets say you have a user with the email, bob@example
.
换句话说,假设您有一个用户使用电子邮件bob@example
.
$user = User::firstOrCreate(['email' => '[email protected]']);
// the below will dump out false because this entry already existed
var_dump($user->wasRecentlyCreated);
Now, lets say [email protected]
doesn't exist.
现在,让我们说不[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);