I have a migration that has the timestamps() method, and then I have a seed to seed this table.

Schema::create('mytable', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->timestamps();
});

The seed looks like this:

DB::table('mytable')->insert([
    [
        'title' => 'My Awesome Title'
    ]
]);

当它全部运行时,请使用:

php artisan migrate:refresh --seed

该项被插入,但created_atupdated_at的值都是0000-00-00 00:00:00为什么设置不正确?

以下是它创建的柱方案:

`created_at` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',

I would like these schemes:

`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

推荐答案

When you insert data not using Eloquent you need to insert timestamps on your own.

如果您使用:

$x = new MyTable();
$x->title = 'My Awesome Title';
$x->save();

you will have timestamp filled correctly (of course you need to create MyTable model first)

EDIT

如果你真的想要,你可以改变:

$table->timestamps();

进入:

$table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(\DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

And if you create model for this table, you should set

$timestamps = false;

以确保Eloquent 者不会试图让他们走上他的道路.

EDIT2

There is also one more important issue. In case you mix setting dates in tables from PHP and in other in MySQL you should make sure that both in both PHP and MySQL there's exact same datetime (and timezone) or you should use the same date comparison as you set in record (either MySQL or PHP). Otherwise when running queries you might get unexpected results for example

SELECT * FROM mytable WHERE DATE(created_at) = CURDATE()

可能与通过传递PHP日期运行查询不同

"SELECT * FROM mytable WHERE DATE(created_at) = '".date('Y-m-d")."'"

because on PHP server it might be for example 2015-12-29 but on MySQL server 2015-12-30

Laravel相关问答推荐

为什么只删除了最后一个Like,而没有删除选中的?

无法使用 Dompdf Laravel 9 加载图像

如何在 Laravel 中将 Select 选项表单插入数据库

Laravel Blade:@stop VS @show VS @endsection VS @append

调用未定义函数 Illuminate\Encryption\openssl_decrypt()

.gitignore 不忽略文件夹

你如何找到 Laravel 外观背后的底层类?

Laravel 4 定义 RESTful 控制器

CRON 作业(job) - LARAVEL - 输出

如何更改 ember-cli 中的 dist 文件夹路径?

如何在 Laravel 4 中使用 SHA1 加密而不是 BCrypt?

禁用Eager的关系

如何运行artisan命令计划:在托管服务器上运行? (Laravel )

在 Laravel 应用程序中在哪里指定应用程序版本?

Laravel 字符串验证以允许空字符串

Class类 App\Http\Controllers\Auth\Request 不存在.

Composer RuntimeException - 无法加载软件包 mews/purifier

Laravel/PHPUnit:断言 json 元素存在而不定义值

为什么`catch (Exception $e)` 不处理这个`ErrorException`?

带有 Xdebug 的 Laravel 5 总是抛出The payload is invalid..