如何在 Laravel 中检查记录是否是新记录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18498518/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:36:31  来源:igfitidea点击:

How to check if a record is new in Laravel?

laraveleloquent

提问by Craig Ward

I recently started using Eloquent.

我最近开始使用 Eloquent。

When I used PHP Active Record, there was a nice function that checked if a record was loaded from the database or is a new instance. Is there something similar in Eloquent that I could use?

当我使用 PHP Active Record 时,有一个很好的函数可以检查记录是从数据库加载还是新实例。我可以使用 Eloquent 中的类似内容吗?

By new I mean:

新我的意思是:

$article = new Article;

whereas one from the database would be

而数据库中的一个将是

$article = Article::find(1);

回答by Hailwood

All laravel models have a ->existsproperty.

所有 Laravel 模型都有一个->exists属性。

More specifically if the model is either loaded from the database, or has been saved to the database since being created the existsproperty will be true; Otherwise it will be false.

更具体地说,如果模型是从数据库加载的,或者自创建以来已保存到数据库中,则该exists属性将为真;否则会是假的。

If you wish to know if the model has been modified since being grabbed from the database, or simply not saved at all (aka if it needs saving) then you can use the ->isDirty()function.

如果您想知道模型自从数据库中获取后是否已被修改,或者根本没有保存(也就是如果它需要保存),那么您可以使用该->isDirty()函数。

The Laravel API is a useful place for this kind of information: http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_isDirtyand often sheds far more light than the default documentation.

Laravel API 是此类信息的有用地方:http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_isDirty 并且通常比默认文档更清晰。

回答by Didier Sampaolo

Your model object has an attribute exactly designed for that. It's wasRecentlyCreated :

您的模型对象具有专门为此设计的属性。这是 wasRecentlyCreated :

$item = Item::firstOrCreate(['title' => 'Example Item']);

if ($item->wasRecentlyCreated === true) {
    // item wasn't found and have been created in the database
} else {
    // item was found and returned from the database
}

回答by shakee93

We can use $appendson model if you will use it many times.. for example to check if the newly created comment is edited after created.

$appends如果您将多次使用它,我们可以在模型上使用......例如检查新创建的评论是否在创建后被编辑。

class Comment extends Model
{
     protected $appends = ['is_edited'];

     public function getIsEditedAttribute()
     {
          return $this->attributes['is_edited'] = ($this->created_at != $this->updated_at) ? true : false;
     }
}

You can use it like

你可以像这样使用它

$comment = Comment::findOrFail(1);

if($comment->is_edited){
      // write your logic here
}

回答by HPage

I am using Laravel Eloquent's updateOrCreate()method to create or update records when importing from a CSV file.

从 CSV 文件导入时,我使用 Laravel Eloquent 的updateOrCreate()方法来创建或更新记录。

$product = $this->updateOrCreate($attributes, $values);

I wanted to count the amount of newly created records and updated records. Since the updateOrCreate()method saves the record to the database upon creation, $product->existswill always return true.

我想计算新创建记录和更新记录的数量。由于该updateOrCreate()方法在创建时$product->exists将记录保存到数据库中,因此将始终返回true.

An alternative is to compare the created_atand updated_attimestamps of the model with the current time:

另一种方法是将模型的时间戳created_atupdated_at时间戳与当前时间进行比较:

if($product->created_at == Carbon::now())
            $created++;
        elseif ($product->updated_at == Carbon::now())
            $updated++;

回答by Wizzard

$article = new Article;
var_dump($article->id); == null

$article = Article::find(1);
var_dump($article->id); == string(1) "1"

so

所以

if ($article->id) {
     // I am existing
} else {
    // I am new
}