更新时间戳(Laravel)

是否可以更新用户而不用触摸时间戳?

我不想完全禁用时间戳。

grtz

暂时禁用它:

$user = User::find(1); $user->timestamps = false; $user->age = 72; $user->save(); 

您可以select在保存后重新启用它们。

这是Laravel 4和5的唯一特征 ,不适用于Laravel 3。

在Laravel 5.2 ,您可以将公共字段$timestampsfalse如下所示:

 $user->timestamps = false; $user->name = 'new name'; $user->save(); 

或者,您可以将选项作为save()函数的parameter passing:

 $user->name = 'new name'; $user->save(['timestamps' => false]); 

为了更深入地理解它是如何工作的,可以在方法performUpdate(Builder $query, array $options = [])看看类\Illuminate\Database\Eloquent\Model performUpdate(Builder $query, array $options = []) \Illuminate\Database\Eloquent\Model

 protected function performUpdate(Builder $query, array $options = []) // [...] // First we need to create a fresh query instance and touch the creation and // update timestamp on the model which are maintained by us for developer // convenience. Then we will just continue saving the model instances. if ($this->timestamps && Arr::get($options, 'timestamps', true)) { $this->updateTimestamps(); } // [...] 

只有公共属性timestamps等于true或者Arr::get($options, 'timestamps', true)返回true (默认情况下,如果$options数组不包含关键timestamps ),该时间戳字段才会更新。

只要这两个中的一个返回falsetimestamps字段不会更新。

添加到Antonio Carlos Ribeiro的答案

如果您的代码要求时间戳超过50%的时间去激活 – 也许您应该禁用自动更新并手动访问它。

在扩展雄辩模型的时候,你可以通过放置来禁用时间戳

UPDATE

public $timestamps = false;

在你的模型里面。

上面的示例很酷,但只适用于单个对象(每次只有一行)。

如果要更新整个集合,这是如何暂时禁用时间戳的简单方法。

 class Order extends Model { .... public function scopeWithoutTimestamps() { $this->timestamps = false; return $this; } } 

现在你可以简单地调用这样的东西:

 Order::withoutTimestamps()->leftJoin('customer_products','customer_products.order_id','=','orders.order_id')->update(array('orders.customer_product_id' => \DB::raw('customer_products.id'))); 

对于试图执行Model::update()调用的Laravel 5.x用户来说,使其可以使用

 Model::where('example', $data) ->update([ 'firstValue' => $newValue, 'updatedAt' => \DB::raw('updatedAt') ]); 

由于Model :: update函数不再需要第二个参数。 ref: laravel 5.0 api

testing并在5.2版本上工作。

我遇到了需要进行大规模更新的情况,涉及到一个连接,所以updated_at导致重复的列冲突。 我修正了这个代码,而不需要一个范围:

 $query->where(function (\Illuminate\Database\Eloquent\Builder $query) { $query->getModel()->timestamps = false; }) 

你也可以使用这个语法:

 Model::where('Y', 'X') ->update(['Y' => 'Z'], ['timestamps' => false]); 

如果您需要更新单个模型查询:

 $product->timestamps = false; $product->save(); 

要么

 $product->save(['timestamps' => false]); 

如果您需要更新多个模型查询使用

 DB::table('products')->...->update(...) 

代替

 Product::...->update(...)