使用 laravel 在字段架构迁移上定义属性 zerofill 和 size

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35108133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:08:42  来源:igfitidea点击:

Define property zerofill and size on field schema migration with laravel

phplaravel

提问by Jérémie Chazelle

How can I define property zerofill and size (2) on field schema migration with Laravel?

如何在 Laravel 的字段架构迁移中定义属性 zerofill 和 size (2)?

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

and this field with zerofill.

和这个领域的零填充。

I would like use my seeder:

我想使用我的播种机:

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

回答by Fiete

Zerofill is not a SQL standard. The shema builder of laravel provides only these ANSI SQL standards.

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

But you can use a workaround to define it with a raw sql statement:

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

create_books.php

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');

回答by WoodyNaDobhar

As mentioned, in order to keep your migrations portable, you'll want to use an accessor to provide that. It'll look something like this:

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

Book.php model

Book.php模型

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