关于webman使用Laravel模型写入时使用自动时间戳,读取时使用格式化的日期格式相差8小时的问题。
在模型中
//指示模型是否主动维护时间戳。
public $timestamps = true;
protected $dateFormat = 'U';
//创建时间
const CREATED_AT = 'create_time';
//更新时间字段
const UPDATED_AT = 'update_time';
protected $casts = ['create_time' => 'datetime:Y-m-d H:i:s', 'update_time' => 'datetime:Y-m-d H:i:s', 'delete_time' => 'timestamp' ];
前端在使用模型自动读取日期格式则相差8小时,webman的 config/app.php 中,也默认配置了 'default_timezone' => 'Asia/Shanghai',
解决方法找到一个
依然在模型中:
protected function serializeDate(DateTimeInterface $date): string
{
return $date->format(Carbon::parse($date)->toDateTimeString());
}
但是感觉这样写有点不靠谱,就不能通过配置文件或者什么来解决吗?请求大家帮忙!
laravel db的确存在这个问题,参考https://blog.csdn.net/Attitude_do_it/article/details/122740434
希望后续能针对laravel提供统一配置方案~
这种只适合单模型,模型关联输出问题无法解决
可以参考这里:https://www.workerman.net/q/8106
这个尝试过问题依旧
@kzhzjdyw888 版本多少 ?
workerman5.0 webman-framework 1.6.14 laravelorm 11.37
timezone.php
AI写了个测试脚本,自己测试下看下哪里有问题。
模型输出没问题,测试脚本追加$records->toArray() 问题也是一样,
array(4) {
["id"]=>
int(5)
["created_at"]=>
string(27) "2025-01-19T13:45:47.000000Z"
["updated_at"]=>
string(27) "2025-01-19T13:45:47.000000Z"
["custom_datetime"]=>
string(19) "2025-01-19 21:45:47"
}
[5]=>
array(4) {
["id"]=>
int(6)
["created_at"]=>
string(27) "2025-01-19T13:45:47.000000Z"
["updated_at"]=>
string(27) "2025-01-19T13:45:47.000000Z"
["custom_datetime"]=>
string(19) "2025-01-19 21:45:47"
}
}
https://learnku.com/docs/laravel/7.x/upgrade/7445#date-serialization
这个是laravel Db v7 更改的特性,大概是为了国际化,输出日期数据带有时区信息,可以按照文档修改自己要的格式
非常感谢
这个方案试过,单独模型没问题,关联模型输出还是有问题。
这边看下是不是放弃内置时间戳管理,使用事件触发写入时间戳,输出时间戳 跟日期双输出。