Php 使用touch()更新laravel中自定义时间戳字段的时间戳
是否有方法使用Php 使用touch()更新laravel中自定义时间戳字段的时间戳,php,laravel-4,orm,eloquent,Php,Laravel 4,Orm,Eloquent,是否有方法使用touch()更新表中Is\u online字段的时间戳,而不是更新laravel中字段创建的 目前我正在使用 User::where('id',$senderId )->update(array('is_online' => date('Y-m-d H:i:s'))); 不,touch方法不是为更新内置时间戳之外的任何内容而编写的,但是如果您愿意,您可以在用户模型中编写自己的函数。像这样的 class User extends Eloquent implements
touch()
更新表中Is\u online
字段的时间戳,而不是更新laravel中字段创建的
目前我正在使用
User::where('id',$senderId )->update(array('is_online' => date('Y-m-d H:i:s')));
不,touch方法不是为更新内置时间戳之外的任何内容而编写的,但是如果您愿意,您可以在用户模型中编写自己的函数。像这样的
class User extends Eloquent implements UserInterface, RemindableInterface {
public function touchOnline()
{
$this->is_online = $this->freshTimestamp();
return $this->save();
}
}
然后用
User::find($senderId)->touchOnline();
还有几行代码,但可能可读性稍微好一点
你可以,如果你好奇的话。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();
一个快速的替代方法是覆盖模型中创建的常数,如
Class User extends Model
{
protected UPDATED_AT = 'is_online';
}
$user->touch();
继续触摸不,如果有什么我想可能会慢一点。但同样,touch也可能比手动更新创建的或更新的要慢。但我们使用Laravel的主要原因不是速度(有速度更快的框架)-可能是可读性和易用性。在这方面,我认为我的建议更好。但是,如果您经常进行更新,我理解您是否想采用更原始的方式:)您应该知道touch()
调用也会更新updated\u的列。而且,更重要的是,引入的更新
事件侦听器也会在任何时候由于某种原因更新模型时刷新is_online
。当由用户编辑其详细信息触发时,这可能没问题,但如果更新是因为管理员正在编辑用户,则可能是不受欢迎的行为。@Arvid注意到了!也许我们可以在调用User::find($senderId)->touch()之前进行一些验证例如,当管理员正在编辑或诸如此类的内容时,不会执行代码>。