简体   繁体   English

在 MySQL 中更新记录时,Laravel 的 useCurrent() 不起作用

[英]Laravel's useCurrent() doesn't work when a record is updated in MySQL

I have recently added a new migration to my database which in its simplest form does something like this我最近在我的数据库中添加了一个新的迁移,它以最简单的形式做了这样的事情

If(Schema::hasTable('some_table')){
    Schema::table('some_table', function (Blueprint $table) {
        $table->dateTime('last_updated')->nullable(false)->useCurrent()->change();
    });
}

According to this answer on SE, Laravel should automatically create and updated the last_record column for me but I am testing this in MySQL 5.7.31 and this is definitely not the case for me.根据这个关于 SE 的答案,Laravel 应该自动为我创建和更新 last_record 列,但我正在 MySQL 5.7.31 中测试这个,这对我来说绝对不是这种情况。 I am using Laravel 7.5 and my PHP version is 7.3.21.我使用的是 Laravel 7.5,我的 PHP 版本是 7.3.21。

Meanwhile, adding CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP manually to my database failed as well.同时,将CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP手动添加到我的数据库也失败了。 So, it seems that it might be an issue with my MySQL database instead of Laravel itself.所以,这似乎是我的 MySQL 数据库而不是 Laravel 本身的问题。 So, I have two questions:所以,我有两个问题:

Is it possible to somehow use Laravel/PHP to always add a default value to a field when nothing is passed on insert or update?当插入或更新时没有传递任何内容时,是否可以以某种方式使用 Laravel/PHP 始终向字段添加默认值?

Edit: @lagbox asked about how I am saving/updating records in my database.编辑:@lagbox 询问我如何在我的数据库中保存/更新记录。 Here is how这是如何

$record= TableModel::where('blah', $blah)
                ->first();

if($record){
    $record->update([
         'blah1' => $blah1,
         'blah2' => $blah2
    ]);
}

You can override the fields that are used for the created_at and updated_at timestamps on the Model that Eloquent will automatically handle:您可以覆盖 Eloquent 将自动处理的模型上用于created_atupdated_at时间戳的created_at

const UPDATED_AT = 'last_updated';

You can also disable a particular timestamp by setting the const to null :您还可以通过将const设置为null来禁用特定时间戳:

const CREATED_AT = null;

Laravel 7.x Docs - Eloquent - Model Conventions - Timestamps UPDATED_AT CREATED_AT Laravel 7.x 文档 - Eloquent - 模型约定 - 时间戳UPDATED_AT CREATED_AT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM