每次保存时如何将 NOW() 保存到 Laravel Eloquent 模型中的同一字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28161786/
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
How to save NOW() to the same field in my Laravel Eloquent model every time I save?
提问by prograhammer
Every time I perform the following:
每次我执行以下操作:
$user = new User;
$user->name = 'John';
$user->save();
I want a field called "modified" to be updated to NOW()
in MySQL. I can't use Laravel's timestamps because I'm only using a single modified field. I could rely on MySQL to do this for me, but I was wondering if there was a way to accomplish this in my Laravel model? Perhaps using a mutator in some way to set this before saving?
我想NOW()
在 MySQL 中更新一个名为“修改”的字段。我不能使用 Laravel 的时间戳,因为我只使用了一个修改过的字段。我可以依靠 MySQL 来为我做这件事,但我想知道是否有办法在我的 Laravel 模型中完成此任务?也许在保存之前以某种方式使用 mutator 来设置它?
As a bonus:how would I do something like this $user->modified = "NOW()"
? (which is obviously wrong, but hopefully demonstrates the point)
作为奖励:我将如何做这样的事情$user->modified = "NOW()"
?(这显然是错误的,但希望能证明这一点)
回答by Joseph Silber
You can accomplish this in the saving
event, for which you can register a callback in you model's boot
method:
您可以在saving
事件中完成此操作,您可以在模型的boot
方法中注册回调:
class User extends Eloquent {
public static function boot()
{
static::saving(function($user)
{
$user->modified = DB::raw('NOW()');
// Alternatively, you can use this:
$user->modified = Carbon\Carbon::now();
});
parent::boot();
}
}