【问题标题】:using touch() to update timestamp of custom timestamp field in laravel使用 touch() 更新 laravel 中自定义时间戳字段的时间戳
【发布时间】:2015-02-20 05:51:19
【问题描述】:

有没有办法使用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


    【解决方案1】:

    不,touch 方法不是为更新内置时间戳以外的任何内容而编写的,但如果您愿意,您可以在用户模型中编写自己的函数。像这样的

    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

    【讨论】:

    • 不,如果有的话,我猜可能会慢一些。但是再一次,触摸可能也比以与您相同的方式手动更新 created_at 或 updated_at 慢。
    • 但是我们使用 Laravel 的主要原因不是速度(有更快的框架)——它可能是可读性和易用性。在这方面,我认为我的提议更好。但是,如果您真的经常进行更新,我理解您是否想采用更原始的方式:)
    【解决方案2】:

    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();
    

    【讨论】:

    • 您应该知道touch() 调用也会更新updated_at 列。而且,更重要的是,引入的updating 事件监听器也将在模型出于某种原因更新时刷新is_online。当它由用户编辑她的详细信息触发时,这可能很好,但如果更新是因为管理员正在编辑用户,则可能是不受欢迎的行为。
    • @Arvid 注意到了!也许我们可以在调用User::find($senderId)->touch();之前做一些验证,例如在管理员编辑时不执行。
    【解决方案3】:

    一种快速的替代方法是覆盖模型中的 CREATED_AT 常量,例如

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

    继续触摸

    【讨论】:

      猜你喜欢
      • 2015-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多