Laravel雄辩和原始sql返回不同的时间戳



我在created_at列中获得了与laravel雄辩和原始sql不同的时间。原始sql给出了正确的时间,而雄辩的则是错误的。我已经正确设置了时区并清除了配置。

控制器

public function index()
{
//returns correct time created_at: "2020-12-08 19:44:30"
$timelines = DB::select('select * from timelines where user_id = ?', [auth()->user()->id]);

//returns wrong time created_at: "2020-12-08T11:44:30.000000Z"
$timelines = Timeline::where('user_id',auth()->user()->id)->get();
return $timelines;
}

型号

class Timeline extends Model
{
use HasFactory;
protected $guarded = [];
}

数据库

{
Schema::create('timelines', function (Blueprint $table) {
$table->id();
$table->integer('user_id')->unsigned()->foreign('user_id')->references("id")->on("users")->onDelete("cascade");
$table->integer('source_id');
$table->string('description');
$table->timestamps();
});
}

原始数据库返回正确的时间,因为DBMS时区是正确的。

但在Eloquent中,created_at字段默认转换为Carbon::class实例。

CCD_ 3将使用您的应用程序的时区配置转换为实时。

因此laravel./config/app.php:的变化

'timezone' => 'Asia/Kuala_Lumpur',

因为根据你的个人资料位置,我假设你在+8时区,您的报告时间日志与Laravel中的默认时区配置UTC相差8小时。

您可以添加一个mutator来更改雄辩返回的格式

public function getCreatedAtAttribute($value) {
return date('Y-m-d H:i:s',strtotime($value));
}

在Timeline模型中添加此函数。

您也可以使用碳方法修改功能

有关更多信息,您可以参考laravel文档。https://laravel.com/docs/8.x/eloquent-mutators#introduction

最新更新