【问题标题】:Laravel casts set date format not workingLaravel强制转换设置日期格式不起作用
【发布时间】:2021-01-02 14:51:31
【问题描述】:

遇到了这样的问题。有一个预订模型。预订有字段 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();
        });
    }

结果

【问题讨论】:

  • 什么“不工作”?.....
  • time_from 和 time_to 格式不是 m-d-Y。投射不工作
  • 好的,你在哪里序列化模型?否则您无法确认它是否“工作”
  • 我首先通过控制器进行预订,但属性 time_from 和 time_to 不起作用转换格式。
  • 你怎么知道他们“不工作”?模型序列化了吗?

标签: laravel


【解决方案1】:

将模型转换为数组或 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),它返回字符串,而不是日期,但它可以在修补程序上作为日期工作,但只有在直接使用Models::find($id)->time_from
  • 谢谢!我理解我的错误。我忘了序列化我的数据。 toArray 或 ToJson()
  • 这对我仍然不起作用。序列化是通过 JsonResource 进行的。使用 Laravel 8。如果我手动访问模型并通过 toArray() 将其转换为数组,它会按预期工作(我得到格式化的日期)。但是使用 JsonResource 集合不会发生这种情况: MyJsonResource::collection($query->get()) 我不敢相信没有人注意到这一点。
  • @John Smith 我认为这是按预期工作的。 $casts 用于序列化(toArraytoJson)。 Api 资源是不同的。您应该明确说明它们返回的内容。
  • 你能给我举个例子,我能从中受益吗?为什么我需要转换为数组才能使用可转换数据?大多数时候我会与实际的模型实例属性进行交互,在这种情况下,我需要使用访问器来转换每个属性吗?
猜你喜欢
  • 1970-01-01
  • 2021-09-10
  • 1970-01-01
  • 2020-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-17
  • 1970-01-01
相关资源
最近更新 更多