如何将日期转换为laravel中的整数

问题描述 投票:1回答:4

我从文档中学到的是,我需要创建一个mutator函数,该函数应该获取该值而不是将其转换为table.But我不断得到SQLSTATE的错误[01000]:警告:1265数据被截断列'valid_to'在第1行(SQL:插入到promotionsnamecity_idvalid_tois_activetypelimitupdated_atcreated_at)值(a,Jadah,2018-02-28,1,1a,1519818982,1519818982) ))

模型的一部分代码:

public function setValidFromValueAttribute($date)
    {
        $this->attributes['valid_from'] = strtotime($date);
    }
    public function setValidToValueAttribute($date)
    {
        $this->attributes['valid_to'] = intval($date);
    }

日期代码的刀片部分是

                <div class="form-group">
                    {!! Form::label('valid_from','Valid From') !!}
                    {!! Form::date('valid_from',\Carbon\Carbon::now()) !!}
                </div>
                <div class="form-group">
                    {!! Form::label('valid_to','Valid Till') !!}
                    {!! Form::date('valid_to',\Carbon\Carbon::now()) !!}
                </div>

迁移部分代码

$table->increments('id');
            $table->string('name')->unique();
            $table->integer('valid_from')->default(1);
            $table->integer('valid_to')->default(1);
            $table->tinyInteger('is_active');
            $table->tinyInteger('type');
            $table->string('city_id')->default('Jadah');
            $table->string('limit')->unsigined();
            $table->integer('updated_at')->unsigined();
            $table->integer('created_at')->unsigined();

任何帮助将受到高度赞赏。

database laravel laravel-5.3 strtotime date-conversion
4个回答
1
投票

在促销模型中,添加:

protected $dates = [
    'valid_from',
    'valid_to'
];

删除线条

public function setValidFromValueAttribute($date)
{
    $this->attributes['valid_from'] = strtotime($date);
}

public function setValidToValueAttribute($date)
{
    $this->attributes['valid_to'] = intval($date);
}

在您的迁移文件中,替换对应于valid_fromvalid_to的行,如下所示

 $table->date('valid_from')
 $table->date('valid_to')

1
投票

转到config/database.php,搜索connections.mysql数组并设置:

'strict' => false,

而你的功能:

public function setValidToValueAttribute($date)
{
    $this->attributes['valid_to'] = strtotime($date);
}

0
投票

如果您给出的限制小于输出,则会出现此错误

EX:82638628721这是你得到的整数值

在您的数据库中,您将类型指定为int(5)。

82638628721> int(5) - >所以发生此错误只是增加valid_to字段的限制


0
投票

我需要做的就是做

protected $dates = [
        'valid_from',
        'valid_to'
    ];

并保持valid_from和valid_to进入迁移

$table->integer('valid_from');
$table->integer('valid_to');

这一切都很好

© www.soinside.com 2019 - 2024. All rights reserved.