php 更新而不触及时间戳(Laravel)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18904853/
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-08-25 18:26:05  来源:igfitidea点击:

Update without touching timestamps (Laravel)

phplaravellaravel-4eloquent

提问by Jannick Vandaele

Is it possible to update a user without touching the timestamps?

是否可以在不触及时间戳的情况下更新用户?

I don't want to disable the timestamps completly..

我不想完全禁用时间戳..

grtz

格茨

回答by Antonio Carlos Ribeiro

Disable it temporarily:

暂时禁用它:

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

You can optionally re-enable them after saving.

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

This is a Laravel 4 and 5 only featureand does not apply to Laravel 3.

这是 Laravel 4 和 5 独有的功能,不适用于 Laravel 3。

回答by Mike

In Laravel 5.2, you can set the public field $timestampsto falselike this:

在 Laravel 中5.2,您可以将公共字段设置$timestampsfalse这样:

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

Or you can pass the options as a parameter of the save()function :

或者您可以将选项作为save()函数的参数传递:

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

For a deeper understanding of how it works, you can have a look at the class \Illuminate\Database\Eloquent\Model, in the method performUpdate(Builder $query, array $options = []):

对于它是如何工作有更深的了解,你可以看看在类\Illuminate\Database\Eloquent\Model中的方法performUpdate(Builder $query, array $options = [])

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

    // [...]

The timestamps fields are updated only if the public property timestampsequals trueor Arr::get($options, 'timestamps', true)returns true(which it does by default if the $optionsarray does not contain the key timestamps).

时间戳字段仅在公共属性timestamps等于trueArr::get($options, 'timestamps', true)返回时更新true(如果$options数组不包含 key ,则默认情况下会更新timestamps)。

As soon as one of these two returns false, the timestampsfields are not updated.

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

回答by Maksim Martianov

Above samples works cool, but only for single object (only one row per time).

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

This is easy way how to temporarily disable timestamps if you want to update whole collection.

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

class Order extends Model
{

 ....

    public function scopeWithoutTimestamps()
    {
        $this->timestamps = false;
        return $this;
    }

}

Now you can simply call something like this:

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

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

回答by azngunit81

To add to Antonio Carlos Ribeiro's answer

添加安东尼奥·卡洛斯·里贝罗的回答

If your code requires timestamps de-activation more than 50% of the time - maybe you should disable the auto update and manually access it.

如果您的代码需要时间戳停用超过 50% 的时间 - 也许您应该禁用自动更新并手动访问它。

In eloquent when you extend the eloquent model you can disable timestamp by putting

在 eloquent 中,当您扩展 eloquent 模型时,您可以通过放置来禁用时间戳

UPDATE

更新

public $timestamps = false;

public $timestamps = false;

inside your model.

在你的模型里面。

回答by hilnius

For Laravel 5.x users who are trying to perform a Model::update()call, to make it work you can use

对于尝试执行Model::update()呼叫的Laravel 5.x 用户,要使其工作,您可以使用

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

As the Model::update function does not take a second argument anymore. ref: laravel 5.0 api

因为 Model::update 函数不再接受第二个参数。参考:laravel 5.0 api

Tested and working on version 5.2.

已测试并在 5.2 版上工作。

回答by Luca C.

If you need to update single modelqueries:

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

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

or

或者

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

If you need to update multiple modelqueries use

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

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

instead of

代替

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

回答by Zane Hooper

I ran into the situation of needing to do a mass update that involves a join, so updated_atwas causing duplicate column conflicts. I fixed it with this code without needing a scope:

我遇到了需要进行涉及连接的批量更新的情况,因此updated_at导致重复列冲突。我在不需要范围的情况下使用此代码修复了它:

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

回答by Marek Skiba

You can also use this syntax:

您还可以使用以下语法:

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

回答by Fredi

I solved it my way, without playing with any configs (not the best way but helpful) :

我以自己的方式解决了这个问题,没有使用任何配置(不是最好的方法,但很有帮助):

$time = $user->updated_at; //write a copy of "updated_at" to $time variable

//do anything you want and let timestamp work as normal

$user->update('updated_at'=> $time) //At the end, rewrite the $time to "updated_at"

Don't forget to make updated_atfillablein your model.

不要忘记updated_atfillable在您的模型中制作。