php Laravel firstOrNew 如何检查它是第一个还是新的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30686880/
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
Laravel firstOrNew how to check if it's first or new?
提问by raphadko
I'm using Laravel's function firstOrNew()
to create a new user or find and update an existing one.
我正在使用 Laravel 的功能firstOrNew()
来创建新用户或查找和更新现有用户。
How can I know, after the object is created, if it existed before or if it's a new object?
在创建对象之后,我如何知道它之前是否存在或者它是否是一个新对象?
The idea is something like this:
这个想法是这样的:
$user = \App\User::firstOrNew([
'email' => $userData->getEmail(),
'name' => $userData->getName(),
]);
if ($user->new) { // some way to check
// user was created now
} else {
//user already existed
}
回答by patricus
You can check the exists
property on the Model.
您可以检查exists
模型上的属性。
if ($user->exists) {
// user already exists
} else {
// user created from 'new'; does not exist in database.
}
回答by mhellmeier
You can check if your user was recently created.
您可以检查您的用户是否是最近创建的。
if ($user->wasRecentlyCreated) {
// new user
} else {
// user already exists
}
(Source: Thomas Kimfrom this answer)
(来源:来自这个答案的Thomas Kim)
回答by Diksha Chaudhary
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, [email protected]
换句话说,假设您有一个用户使用电子邮件 [email protected]
$user = User::firstOrCreate(['email' => '[email protected]']);
var_dump($user->wasRecentlyCreated);
// the above will dump out false because this entry already existed otherwise true.
// 上面的内容会转储 false,因为该条目已经存在,否则为 true。
回答by Nizar El Berjawi
You can always check for an ID (or any other unique primary key) in the model.
您始终可以检查模型中的 ID(或任何其他唯一主键)。
$user = \App\User::firstOrNew([
'email' => $userData->getEmail(),
'name' => $userData->getName(),
]);
if($user->id) {
// The user exists and was retrieved from the database...
}
if (!$user->id) {
// The user was not found in the database and a new User model was created...
}
It is important to keep in mind that after you persist the model using $user->save()
, you will NOT be able to use $user->id
to check if it was found in the database or not. This is because Eloquent populates all the attributes of the new model after it is saved.
重要的是要记住,使用 持久化模型后$user->save()
,您将无法使用$user->id
它来检查它是否在数据库中找到。这是因为 Eloquent 会在新模型保存后填充新模型的所有属性。