Laravel类型转换设置日期格式无效。

5
遇到了这样的问题。有一个 Booking 模型,它有 time_from 和 time_to 两个字段。当我调用某种 Booking 时,想要使时间格式不同。尝试使用 $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();
        });
    }

结果

输入图像描述


1
我通过控制器获取了第一个Booking,但是time_from和time_to属性不起作用,需要进行格式转换。 - Arthur
$booking = App\Models\Booking::first(); dd($booking);$booking = App\Models\Booking::first(); dd($booking); - Arthur
不要对模型进行序列化... - lagbox
上次我们谈到了,在你的代码中哪里进行了模型实例的序列化(转换为数组或JSON)? - lagbox
有人知道 Laravel 7.x 中的 $dates 被移动到哪里了吗?我的意思是,我想他想要使用 cast 来使用 $dates ,因为现在像以前一样,在 eloquent 模型中 $dates 不再起作用。 - Benyamin Limanto
显示剩余11条评论
1个回答

6

当您将模型转换为数组或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 8.x上,它甚至没有将time_from更改为carbon,我的项目有什么问题吗?我的意思是我和你一样做了同样的事情,只是不同的列。我尝试了dd($data->time_from),它返回字符串,而不是日期,但在tinker上作为日期使用时它可以工作,但只有在直接使用Models::find($id)->time_from时。 - Benyamin Limanto
谢谢!我明白我的错误了。我忘记对我的数据进行序列化。需要使用toArray或toJson()方法。 - Arthur
这对我仍然不起作用。序列化是通过JsonResource进行的。使用Laravel 8。如果我手动访问模型并通过toArray()将其转换为数组,则可以按预期工作(我获得格式化日期)。但是,使用JsonResource集合时不会发生这种情况:MyJsonResource::collection($query->get())我无法相信没有人注意到这一点。 - John Smith
@John Smith 我认为这个工作是按预期进行的。$casts 用于序列化(toArraytoJson)。Api 资源是不同的。你应该明确它们返回什么。 - IGP
你能否给我一个例子,说明我如何从中受益?为什么我需要将数据转换为数组才能使用可转换的数据?大多数情况下,我与实际模型实例属性进行交互,在这种情况下,我需要使用访问器来转换每个属性吗? - John Smith
您可以使用Carbon的format方法获取格式化后的值。 {{ $model->time_from->format('m-d-Y'); }}。您可能需要使用Carbon实例来执行其他操作,例如获取日期差异。 - IGP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接