mariadb 如何使用架构构建器添加虚拟列?

huwehgph  于 2023-05-17  发布在  其他
关注(0)|答案(3)|浏览(200)

我创建了一个这样的表

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`

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

oymdgrw7

oymdgrw71#

我知道这是一个老问题,但是从Laravel 5.3开始,有一种方法可以使用模式构建器来完成它,所以我想我会把它放在这里以确保完整性。
您可以使用laravel 5.3列修饰符virtualAs或storedAs。
因此,要创建一个虚拟生成列,以便在每次查询时计算,您可以像这样创建列:

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

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

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

rdrgkggo2#

你也可以使用Laravel Events来实现相同的结果,而不使用storedAs或virtualAs。供参考: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;
        });
    }
}
e4eetjau

e4eetjau3#

我不认为你可以用schema builder(如果我错了,请有人纠正我)来做这件事,但你总是可以“回退到”原始SQL:

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

相关问题