Eloquent 模型未更新 updated_at 时间戳

Eloquent model not updating updated_at timestamp

我正在使用 Laravel 5.1。为了简单起见,我有以下代码

迁移:

Schema::create('sitemap_data', function (Blueprint $table) {
    // Primary and foreign keys
    $table->increments('id');
    $table->string('postUrl');
    // Database functions
    $table->timestamps();
});

这是我在其他地方使用的代码

$sitemapData = SitemapData::firstOrNew([
                'postUrl' => $post
            ]);
$sitemapData->save();

现在,根据 Laravel 文档

Again, the updated_at timestamp will automatically be updated, so there is no need to manually set its value

updated_at 值应在 table 中更新。然而,这并没有发生。

它只在第一次插入时设置,而不是在更新时设置。当我手动做的时候,像这样

$sitemapData = SitemapData::firstOrNew([
                    'postUrl' => $post
                ]);
$sitemapData->updated_at = Carbon::now();
$sitemapData->save();

有效。但是,文档说这应该是自动发生的,那么这里有什么问题呢?

我已经在 Whosebug 上的一些网站上搜索了这个问题,但我找到了 Laravel 3 或 4.1、4.2 等

我该如何正确地做到这一点?

如评论中所述,如果模型未更改,则不会更新时间戳。但是,如果您需要更新它们,或者想检查是否一切正常,请使用 $model->touch() - 更多 here

其实是有可能的:

$model->updated_at = Carbon::now();
$model->save(['timestamps' => FALSE]);

这将正确保存 updated_at 到现在。如果您不确定模型的任何列是否已更改,但无论如何您都想更新 updated_at - 这是要走的路。

是的 Musterknabe 所做的是正确的,但他还应该检查他的模型 SitemapData.php 它应该已经设置$timestamps = true;

<?php 

 class SitemapData extends Eloquent {

        public $timestamps = true;
}

问题中的情况并非如此,但如果您使用查询生成器而不是 Eloquent 模型,则会发生同样的问题。

如果你这样做

DB::table('users')->where()->update()

而不是

User::where()->update()

updated_at不会再更新了。

转到 phpmyadmin 和 select 你的数据库和 select table 点击上面的 SQL 选项卡并键入例如这样的内容:

UPDATE `boshogriq_table` SET  `updated_at`= DATE_ADD(`created_at`, INTERVAL 1 MINUTE)
 WHERE  `updated_at` > DATE_ADD(`created_at`, INTERVAL 10 MINUTE)

运行 按“开始”按钮。 Laravel 不允许你这样做