【问题标题】:Extending the Schema Builder扩展模式构建器
【发布时间】:2013-07-26 06:34:42
【问题描述】:

谁能详细地告诉我如何扩展 Illuminate\Database\Schema 以添加一个 zerofill 函数并修改当前整数函数以获取一个长度参数,而实际上并没有修改任何供应商文件。

谢谢。

编辑:或者有没有办法使用 Schema Builder 手动添加一列,我只是错过了周五下午头重脚轻的原因?

编辑:采用 Gareth Oakley 建议的方法,在 Schema::create() 之后添加 DB::statement() 调用:

<?php

    class CreateExamplesTable extends Migration {

        public function up()
        {
            Schema::create('examples', function(Blueprint $table)
            {
                $table->engine = 'InnoDB';

                $table->increments('id')->unsigned();
                $table->integer('account_id')->unsigned();
                $table->string('card_id', 20)->nullable();
                $table->boolean('active')->default(true);
                $table->timestamps();

                $table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade')->onUpdate('cascade');
            });

            DB::statement('ALTER TABLE examples ADD invoice_id INT(6) UNSIGNED ZEROFILL NOT NULL AFTER card_id');
        }

        public function down()
        {
            Schema::drop('examples');
        }
    }

【问题讨论】:

  • Laravel 不提供这样的功能。您可以选择一种 smallinteger/integer/biginteger 类型 - 选择最适合的一种。就个人而言,我不会在数据库端使用 zerofill。我会在应用程序端格式化输出。
  • 我在下面发布了一个答案 - 但同意了。我通常会留下与数据如何在数据库之外呈现相关的任何内容,并将其放在我的视图中。你可以使用str_pad - php.net/manual/en/function.str-pad.php

标签: laravel laravel-4


【解决方案1】:

我以前不需要使用 zerofills - 我猜你指的是这个功能:

与可选(非标准)属性结合使用时 ZEROFILL,空格的默认填充被零替换。为了 例如,对于声明为 INT(4) ZEROFILL 的列,值 5 是 检索为 0005。

鉴于它不是标准 SQL 属性,您可能必须使用 DB 类手动创建列:

DB::statement('ALTER TABLE MyTable ADD MyColumn INT UNSIGNED ZEROFILL NOT NULL');

架构构建非常适合绝大多数不需要使用数据库特定功能但看起来其他人有时不得不做类似事情的情况:

Make column not nullable in a Laravel migration

【讨论】:

  • 尽管这实际上不是我真正想做的;它仍然是最简单的常识实现,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-06
  • 2013-11-11
相关资源
最近更新 更多