【发布时间】:2013-09-01 03:40:50
【问题描述】:
我最近开始使用 Eloquent。
当我使用 PHP Active Record 时,有一个很好的函数可以检查记录是从数据库中加载的还是新实例。我可以使用 Eloquent 中的类似功能吗?
我的意思是新的:
$article = new Article;
而数据库中的一个是
$article = Article::find(1);
【问题讨论】:
我最近开始使用 Eloquent。
当我使用 PHP Active Record 时,有一个很好的函数可以检查记录是从数据库中加载的还是新实例。我可以使用 Eloquent 中的类似功能吗?
我的意思是新的:
$article = new Article;
而数据库中的一个是
$article = Article::find(1);
【问题讨论】:
$article = new Article;
var_dump($article->id); == null
$article = Article::find(1);
var_dump($article->id); == string(1) "1"
所以
if ($article->id) {
// I am existing
} else {
// I am new
}
【讨论】:
所有 laravel 模型都有一个 ->exists 属性。
更具体地说,如果模型是从数据库中加载的,或者自创建后已保存到数据库中,exists 属性将为 true;否则为假。
如果您想知道模型在从数据库中获取后是否已被修改,或者根本没有保存(也就是需要保存),那么您可以使用->isDirty() 函数。
Laravel API 是存放此类信息的好地方: http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_isDirty 并且通常比默认文档更清楚。
【讨论】:
$model->exists() 方法混淆,它会做其他事情,比如计算数据库中的行数,如果 count > 0 则返回 :)
从 CSV 文件导入时,我正在使用 Laravel Eloquent 的 updateOrCreate() 方法来创建或更新记录。
$product = $this->updateOrCreate($attributes, $values);
我想计算新创建记录和更新记录的数量。由于updateOrCreate() 方法在创建时将记录保存到数据库中,所以$product->exists 将始终返回true。
另一种方法是将模型的created_at 和updated_at 时间戳与当前时间进行比较:
if($product->created_at == Carbon::now())
$created++;
elseif ($product->updated_at == Carbon::now())
$updated++;
【讨论】:
我们可以在模型上使用$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;
}
}
你可以像这样使用它
$comment = Comment::findOrFail(1);
if($comment->is_edited){
// write your logic here
}
【讨论】:
您的模型对象具有专门为此设计的属性。它是最近创建的:
$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
}
关于存在变量的工作方式与 wasRecentlyCreated 变量之间的更多说明(从下面 CJ Dennis 的评论中复制)
/* Creating a model */
$my_model = new MyModel;
$my_model->exists === false;
$my_model->wasRecentlyCreated === false;
$my_model->save();
$my_model->exists === true;
$my_model->wasRecentlyCreated === true;
与从之前的请求中加载模型相反:
/* Loading a Model */
$my_model = MyModel::first();
$my_model->exists === true;
$my_model->wasRecentlyCreated === false;
【讨论】:
wasRecentlyCreated 指示模型是否在当前请求生命周期中插入。因此,即使数据库中缺少记录,它也只会在保存后返回true。
/* Creating a model */ $my_model = new MyModel; $my_model->exists === false; $my_model->wasRecentlyCreated === false; $my_model->save(); $my_model->exists === true; $my_model->wasRecentlyCreated === true; /* Loading a Model */ $my_model = MyModel::first(); $my_model->exists === true; $my_model->wasRecentlyCreated === false;
false,然后再次查询新创建的Item::firstOrCreate(['title' => 'Example Item']);,然后Item::where(['title' => 'Example Item'])->first()->wasRecentlyCreated,这将返回false。请记住获取创建方法的返回值。但问题是,在创建相关模型和查询新创建的模型时。