如何在 Laravel 中检查记录是否是新记录? [英] How to check if a record is new in Laravel?

查看:14
本文介绍了如何在 Laravel 中检查记录是否是新记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用 Eloquent.

I recently started using Eloquent.

当我使用 PHP Active Record 时,有一个很好的函数可以检查记录是从数据库加载还是新实例.我可以使用 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?

我的意思是:

$article = new Article;

而数据库中的一个是

$article = Article::find(1);

推荐答案

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

All laravel models have a ->exists property.

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

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

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

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.

Laravel API 是提供此类信息的有用场所:http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_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_isDirty and often sheds far more light than the default documentation.

这篇关于如何在 Laravel 中检查记录是否是新记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆