Laravel 和 MySQL 在 DateTime 的情况下不能很好地发挥作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24096730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel and MySQL not playing well in case of DateTime
提问by Rajat Saxena
I created a webapp using Laravel and SQLite,everything was going great.Now,I want to use MySQL as database but now I am unable to add data to my tables.
我使用 Laravel 和 SQLite 创建了一个 web 应用程序,一切都很顺利。现在,我想使用 MySQL 作为数据库,但现在我无法将数据添加到我的表中。
This is the field from my migration:
这是我迁移的字段:
$table->dateTime('last_updated')->nullable();
and this is how I am populating the field using laravel:
这就是我使用 laravel 填充字段的方式:
$client->last_updated = time();
But it is giving me error like:
但它给了我这样的错误:
Illuminate \ Database \ QueryException
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '1402140378' for column 'last_updated' at row 1 (SQL: update `clients` set `last_updated` = 1402140378 where `id` = 1)
Any help will be appreciated.
任何帮助将不胜感激。
回答by Marwelln
$table->dateTime
creates an DATETIME
column in your database that expects a value of YYYY-MM-DD HH:ii:ss
. What you're inserting is a unix timestamp.
$table->dateTime
DATETIME
在您的数据库中创建一个期望值为 的列YYYY-MM-DD HH:ii:ss
。你插入的是一个unix时间戳。
You can either use Carbon
(requires use Carbon\Carbon
at the top of your file),
您可以使用Carbon
(需要use Carbon\Carbon
在文件顶部),
$client->last_updated = Carbon::now()
$client->last_updated = date('Y-m-d H:i:s')
or PHP's DateTime
class to insert the current datetime to the database..
或 PHP 的DateTime
类将当前日期时间插入到数据库中..