每次保存时如何将 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

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

How to save NOW() to the same field in my Laravel Eloquent model every time I save?

phplaravellaravel-4eloquent

提问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 savingevent, for which you can register a callback in you model's bootmethod:

您可以在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();
    }

}