使用touch()更新laravel中自定义时间戳字段的时间戳

问题描述 投票:3回答:3

有没有办法使用touch()更新表中的is_online字段的时间戳,而不是更新laravel created_at中的Eloquent ORM字段

目前我正在使用

User::where('id',$senderId )->update(array('is_online' => date('Y-m-d H:i:s')));
php laravel-4 orm eloquent
3个回答
6
投票

不,除了内置时间戳之外,不会编写触摸方法来更新任何内容,但是如果您愿意,可以在用户模型中编写自己的函数。像这样的东西

class User extends Eloquent implements UserInterface, RemindableInterface {

    public function touchOnline()
    {
        $this->is_online = $this->freshTimestamp();
        return $this->save();
    }
}

然后用你的旧代码替换

User::find($senderId)->touchOnline();

还有一些代码行,但可能稍微有些可读性。

如果你很好奇,你可以find the code behind the touch function here


0
投票

Laravel 4.2

class User extends Eloquent implements UserInterface, RemindableInterface
{
    public static function boot()
    {
        parent::boot();
        /*
        static::creating(function($table) {
            $table->foo = 'Bar';
        });
        */
        static::updating(function($table) {
            $table->is_online = $this->freshTimestamp();
            // $table->something_else = 'The thing';
        });
    }
}

用法。只需调用原生触摸方法即可。

User::find($senderId)->touch();

0
投票

一个快速的替代方法是覆盖模型中的CREATED_AT常量

Class User extends Model
{
    protected UPDATED_AT = 'is_online';
}
$user->touch();

继续抚摸吧

© www.soinside.com 2019 - 2024. All rights reserved.