gpt4 book ai didi

php - Laravel 在保存到数据库之前改变日期?

转载 作者:可可西里 更新时间:2023-11-01 08:03:36 25 4
gpt4 key购买 nike

我在日期选择器中按以下格式选择了一个日期

Y-m-d g:i A

所以使用 AM/PM,它在我的输入字段中显示以下内容,这是正确的

enter image description here

当我在场外提交表单时,Laravel 不会更新记录,因为格式对于我在 mysql 中的 DATETIME 字段是未知的。

我的“日期”字段被添加到 $dates 数组中,因此它应该被 Laravel 解析

I tried using a Mutator on my Model as following, without success

public function setDateAttribute($value)
{
$this->attributes['date'] = Carbon::createFromFormat('Y-m-d g:i A', $value)->format('Y-m-d H:i:s');
}

原始值未更新。知道我可能做错了什么吗?

谢谢

最佳答案

看看 Laravel 的 date mutators , 这会为您处理进出数据库的访问日期和更改日期,就像处理 created_at 和其他默认日期一样。

基本上,您需要将 date 字段添加到模型的 $dates 数组中,如下所示:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
'created_at', // Add if you're using timestamps on the model
'updated_at', // Add if you're using timestamps on the model
'deleted_at', // Add if you're using softDeletes on the model
'date'
];
}

这样,当模型持久化到数据库时,它是作为 DATETIME 完成的,而当它从数据库中读入您的模型时,它将是 Carbon 实例

关于php - Laravel 在保存到数据库之前改变日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40860763/

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