【问题标题】:Define property zerofill and size on field schema migration with laravel使用 laravel 定义字段模式迁移的属性 zerofill 和大小
【发布时间】:2017-12-19 10:52:45
【问题描述】:

如何在使用 Laravel 进行字段架构迁移时定义属性 zerofill 和 size (2)?

Schema::create('books', function (Blueprint $table) {
    $table->integer('reference')->length(2);
});

这个字段用 zerofill。

我想使用我的播种机:

public function run()
{
    Book::create
    ([
        'reference' => 01
    ]);
}

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    Zerofill 不是 SQL 标准。 laravel 的 shema builder 只提供这些 ANSI SQL 标准。

    但是您可以使用一种变通方法来使用原始 sql 语句来定义它:

    create_books.php

    Schema::create('books', function (Blueprint $table) {
        $table->integer('reference');
    });
    DB::statement('ALTER TABLE books CHANGE reference reference INT(2) UNSIGNED ZEROFILL NOT NULL');
    

    【讨论】:

    • 您可以使用访问器执行此操作。 Similar Problem 问题是:如果必须在访问器中手动填充,是否需要在数据库中存储前导零?
    【解决方案2】:

    如前所述,为了保持迁移的可移植性,您需要使用访问器来提供它。它看起来像这样:

    Book.php 模型

    public function getReferenceAttribute($value)
    {
        if($value){
            return str_pad($value, 2, '0', STR_PAD_LEFT);
        }else{
            return null;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-21
      • 2015-02-03
      • 2017-12-21
      • 2018-06-07
      • 1970-01-01
      相关资源
      最近更新 更多