gpt4 book ai didi

Laravel 转换设置日期格式不起作用

转载 作者:行者123 更新时间:2023-12-05 02:02:58 26 4
gpt4 key购买 nike

遇到这样的问题。有一个预订模型。预订有字段 time_from 和 time_to。当我调用某种预订时,希望格式不同。尝试使用 $casts = ['time_from' => 'datetime:m-d-Y'];不工作!可能是什么问题???

模型

class Booking extends Model
{
use HasFactory;
protected $casts = [
'time_from' => 'datetime:m-d-Y',
'time_to' => 'datetime:m-d-Y'
];
protected $dateFormat = 'm-d-y';
protected $fillable = [
'room_id',
'time_from',
'time_to',
'first_name',
'last_name',
'phone',
'email',
'special_requirements',
'when_wait_you',
];

public function room(){
return $this->belongsTo(Room::class);
}
}

迁移

    public function up()
{
Schema::create('bookings', function (Blueprint $table) {
$table->id();
$table->bigInteger('room_id');
$table->dateTime('time_from');
$table->dateTime('time_to');
$table->string('first_name');
$table->string('last_name');
$table->string('phone');
$table->string('email');
$table->text('special_requirements')->nullable();
$table->string('when_wait_you')->nullable();
$table->timestamps();
});
}

结果

enter image description here

最佳答案

转换是在您将模型转换为数组或 json 格式时完成的。

class Booking extends Model
{
use HasFactory;
protected $casts = [
'time_from' => 'datetime:m-d-Y',
];
}
App\Models\Booking::first()->time_from

=> Illuminate\Support\Carbon { ... }
App\Models\Booking::first()->toArray()['time_from'] 

=> '01-02-2021'
App\Models\Booking::first()->toJson()

=> "{... "time_from":"01-02-2021", ....}"

关于Laravel 转换设置日期格式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65540420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com