Laravel 递增字段时禁用自动 "updated_at"

Laravel Disable auto "updated_at" when Incrementing Fields

我正在增加 table

中的一些总字段
$model->total_comments += 1;
$model->save();

然而,这会触发 updated_at 的更新日期。我想在这些情况下禁用它。我知道我可以手动完成并完全禁用时间戳字段的自动更新。但希望有一个简单的方法来做到这一点。

编辑:

从我的代码中添加示例。请注意,此模型上没有设置观察者。

namespace App\Models;

class Language extends \Illuminate\Database\Eloquent\Model
{

}

$router->get('/test', function () {
    $model = \App\Models\Language::find(1);

    $model->words_total = $model->words_total + 1;
    $model->save(['timestamps' => false]);

    return 'boo';
});

注意 目前框架中存在一个错误,导致第一个解决方案无法运行。如果它得到修复,我会及时更新 post。 Github issue


您可以将选项数组传递给 save() 并禁用该保存的时间戳:

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

当然你也可以在模型上设置属性,但是如果你有可能继续使用,这将需要你将它设置回true相同模型实例:

$model->timestamps = false;
$model->save();
$model->timestamps = true;

暂时禁用它

$model->total_comments += 1;
$model->timestamps = false;
$model->save();

您可以在保存前通过执行此操作暂时禁用时间戳。

$model->timestamps = false;

解决方案一:

$model = Table::find($planId);
$model->timestamps = false;
$model->increment('popularity');
$model->save();

方案二:

DB::table('Table')
->where(‘id’, $planId)
->increment(‘popularity’,1)

了解更多信息 https://medium.com/@panjeh/laravel-eloquent-model-increment-with-or-without-updating-timestamps-1274c6cd7f52