Define property zerofill and size on field schema migration with laravel

前端 未结 2 1151
眼角桃花
眼角桃花 2020-12-20 01:46

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

Schema::create(\'books\', function (Blueprint $table) {
    $table-&g         


        
相关标签:
2条回答
  • 2020-12-20 02:05

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

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

    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');
    
    0 讨论(0)
  • 2020-12-20 02:30

    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

    public function getReferenceAttribute($value)
    {
        if($value){
            return str_pad($value, 2, '0', STR_PAD_LEFT);
        }else{
            return null;
        }
    }
    
    0 讨论(0)
提交回复
热议问题