通过laravel Eloquent模型以dd / mm / yyyy插入日期格式 [英] Insert date format in dd/mm/yyyy through laravel Eloquent Model

查看:115
本文介绍了通过laravel Eloquent模型以dd / mm / yyyy插入日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel Eloquent,并且我有一个带有日期字段的模型。

I am using Laravel Eloquent and I have a model with a date field.

我的日期值为 dd / mm / yyyy
通过导入CSV文件输入到系统中的数据。文件中的日期值格式为 dd / mm / yyyy

如何通过 dd / mm / yyyy 插入日期

How can I insert a date with format of dd/mm/yyyy through the model of laravel eloquent.

我的模型问题如下。

class Issue extends Model
{
    protected $table = 'issue';
    protected $primaryKey = 'ACC_NO';
    protected $keyType = 'String';
     public $incrementing = false;
    public $timestamps = false;
    protected $dates= ['issue_date','due_date'];



   public function setIssueDateAttribute($value)
    {

     $this->attributes['issue_date'] = Carbon::createFromFormat('d/m/Y', $value)->toDateString();
  }
    public function setDueDateAttribute($value)
    {
   $this->attributes['due_date'] = Carbon::createFromFormat('d/m/Y', $value)->toDateString();
  }
}

但仍未将其设置为mysql数据库中的dd / mm / yyyy

But still it is not set as in the format of dd/mm/yyyy in mysql database

推荐答案

似乎您正在尝试以特定格式$ b存储或检索日期值$ b数据库接受Ymd格式的数据。ie(yyyy-mm-dd)
我建议您为各个模型定义一个访问器。
Eg

It seems you are trying to store or retrieve the date value in specific format the database accept the data in Y-m-d format.i.e(yyyy-mm-dd) I would suggest you to Defining An Accessor for the respective model. E.g

public function getCreatedAtAttribute($value)
    {
        $date = Carbon::parse($value);
        return $date->format('d-m-Y');
    }

注意:
使用Carbon\Carbon;

Note: use Carbon\Carbon;

在课程开始之前在模型文件中使用此功能。

这篇关于通过laravel Eloquent模型以dd / mm / yyyy插入日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆