使用 Laravel 5.4 在数据库中插入日期和时间
Insert Date and time in dataBase using Laravel 5.4
我想插入当前日期和时间的日期,这是我的代码:
$test = new Test;
$dt = new DateTime;
$test->date = $dt->format('m-d-y H:i:s');
$test->users_id = Auth::user()->id;
$test->save();
问题是它不适合数据库中的正确日期,它插入:
2007-02-18 09:52:41
为什么要以数据库中未定义的自定义格式存储它?我认为是错误的想法。
根据我的正确解决方案:
我假设您将日期和时间存储在 MySQL 数据库中作为时间戳值,默认值为 null
。像这样:
$table->timestamp('your-date-column')->nullable();
当点击控制器方法时:
public function yourControllerMethod(Request $request)
{
// Don't forget to import the Carbon namespace
$dateTime = Carbon::parse($request->your_datetime_field);
$request['your_datetime_field'] = $dateTime->format('Y-m-d H:i:s');
}
当检索 your_datetime_field
时,默认情况下将其解析为 Carbon
实例,如下所示:
Test.php
/**
* The dates that will be mutated to Carbon instance.
*
* @return array
*/
protected $dates = [
'your_datetime_field',
];
现在您已经在运行时将字段转换为 Carbon 实例,您可以根据需要自由编辑日期和时间格式。
不是正确的解决方案:
警告,我还没有测试过这个,但我想它应该可以工作..
如果你还想在数据库字段中保存为自定义格式,保存为字符串格式,默认值为null
。
$table->string('your-date-column')->nullable();
然后在运行时将其转换为 datetime 类型。
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'your_datetime_field' => 'datetime:Y-m-d',
];
再一次,我建议不要走错方向,除非你知道你在做什么以及后果是什么。
你懂的。
我想插入当前日期和时间的日期,这是我的代码:
$test = new Test;
$dt = new DateTime;
$test->date = $dt->format('m-d-y H:i:s');
$test->users_id = Auth::user()->id;
$test->save();
问题是它不适合数据库中的正确日期,它插入:
2007-02-18 09:52:41
为什么要以数据库中未定义的自定义格式存储它?我认为是错误的想法。
根据我的正确解决方案:
我假设您将日期和时间存储在 MySQL 数据库中作为时间戳值,默认值为 null
。像这样:
$table->timestamp('your-date-column')->nullable();
当点击控制器方法时:
public function yourControllerMethod(Request $request)
{
// Don't forget to import the Carbon namespace
$dateTime = Carbon::parse($request->your_datetime_field);
$request['your_datetime_field'] = $dateTime->format('Y-m-d H:i:s');
}
当检索 your_datetime_field
时,默认情况下将其解析为 Carbon
实例,如下所示:
Test.php
/**
* The dates that will be mutated to Carbon instance.
*
* @return array
*/
protected $dates = [
'your_datetime_field',
];
现在您已经在运行时将字段转换为 Carbon 实例,您可以根据需要自由编辑日期和时间格式。
不是正确的解决方案:
警告,我还没有测试过这个,但我想它应该可以工作..
如果你还想在数据库字段中保存为自定义格式,保存为字符串格式,默认值为null
。
$table->string('your-date-column')->nullable();
然后在运行时将其转换为 datetime 类型。
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'your_datetime_field' => 'datetime:Y-m-d',
];
再一次,我建议不要走错方向,除非你知道你在做什么以及后果是什么。
你懂的。