Laravel timestamps() doesn't create CURRENT_TIMESTAMP

◇◆丶佛笑我妖孽 提交于 2019-12-04 00:48:07

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

If you use:

$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

If you really want it you can change:

$table->timestamps();

into:

$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;

to make sure Eloquent won't try to set them on his way.

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

might be different than running query with passing PHP date

"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

For later versions, you can simply use. (source)

$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();

i would use the carbon library if i am seeding in the timestamps and set that up in the factory. if not you could do something like this :

$timestamps = false;

and i would remove the the $table->timestamps(); from the migration if i am not going to use it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!