简体   繁体   English

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

[英]Laravel eloquent and raw sql return different timestamp

I'm getting different time in the created_at column from laravel eloquent and raw sql.我从 laravel eloquent 和原始 sql 在 created_at 列中得到不同的时间。 The raw sql gives the correct time while the eloquent is wrong.原始 sql 给出了正确的时间,而 eloquent 是错误的。 I've already setup the timezone properly and clear config.我已经正确设置了时区并清除了配置。

Controller Controller

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

Model Model

class Timeline extends Model
{
    use HasFactory;

    protected $guarded = [];

}

Database数据库

{
    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();
    });
}

The Raw Database returns correct time because DBMS time zone is correct.原始数据库返回正确的时间,因为 DBMS 时区正确。

but in Eloquent, created_at field converts into an Carbon::class instance by default.但在 Eloquent 中, created_at字段默认转换为Carbon::class实例。

and Carbon::class will use timezone configuration of your app to convert to real time.Carbon::class将使用您的应用程序的时区配置转换为实时。

so change in laravel ./config/app.php :所以改变 laravel ./config/app.php

'timezone' => 'Asia/Kuala_Lumpur',

because i suppose you are in +8 Timezone based on your profile location, and your reporting time log are 8 hours difference from UTC the default time zone config in Laravel.因为我想根据您的个人资料位置,您处于 +8 时区,并且您的报告时间日志与UTC时区相差 8 小时,Laravel 中的默认时区配置。

You can add a mutator to change format returned by eloquent您可以添加一个 mutator 来更改 eloquent 返回的格式

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

add this function in your Timeline model.在您的时间线 model 中添加此 function。

you can also modify function by using carbon methods您还可以使用碳方法修改 function

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM