【问题标题】:How to add a virtual column with the schema builder?如何使用架构生成器添加虚拟列?
【发布时间】:2015-03-01 05:47:12
【问题描述】:

我正在创建一个这样的表,

Schema::create('booking_segments', function (Blueprint $table) {
    $table->increments('id');

    $table->datetime('start')->index();
    $table->integer('duration')->unsigned();
    $table->string('comments');
    $table->integer('booking_id')->unsigned();
    $table->foreign('booking_id')->references('id')->on('bookings')->onDelete('cascade');
});

但我想多加一列。在原始 SQL 中看起来像这样:

ALTER TABLE booking_segments ADD COLUMN `end` DATETIME AS (DATE_ADD(`start`, INTERVAL duration MINUTE)) PERSISTENT AFTER `start`

如何将它添加到我的迁移中?我还需要在上面创建一个索引。

【问题讨论】:

    标签: laravel mariadb


    【解决方案1】:

    我知道这是一个老问题,但自 Laravel 5.3 以来就有一种使用模式构建器的方法,所以我想我会把它放在这里以保持完整性。

    你可以使用 laravel 5.3 column modifiers virtualAs 或 storedAs。

    因此,要创建一个虚拟生成的列以在每个查询中计算,您可以这样创建列:

    $table->dateTime('created_at')->virtualAs( 'DATE_ADD(`start`, INTERVAL duration MINUTE)' );
    

    要创建存储生成的列,您可以像这样创建列:

    $table->dateTime('created_at')->storedAs( 'DATE_ADD(`start`, INTERVAL duration MINUTE)' );
    

    【讨论】:

      【解决方案2】:

      我不认为你可以使用架构构建器来做到这一点(如果我错了,请有人纠正我)但你总是可以“退回”到原始 SQL:

      DB::statement('ALTER TABLE booking_segments ADD COLUMN `end` DATETIME AS (DATE_ADD(`start`, INTERVAL duration MINUTE)) PERSISTENT AFTER `start`');
      

      【讨论】:

        【解决方案3】:

        你也可以使用 Laravel 事件来获得相同的结果,而无需使用 存储方式或虚拟方式。 供参考:Laravel: performing some task on every insert/update when using Query Builder or Eloquent ORM

        这就是我的做法:

        class MyModel extends Model
        {
            /** .... **/
        
            /**
             * The "booted" method of the model.
             *
             * @return void
             */
            protected static function booted()
            {
                static::creating(function ($option) {
                    $option->column1 = $option->column2 + 2;
                });
        
                static::updating(function ($option) {
                    $option->column1 = $option->column2 + 2;
                });
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-27
          • 2013-02-28
          • 2017-10-27
          • 1970-01-01
          相关资源
          最近更新 更多