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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27749887/
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 10:37:57  来源:igfitidea点击:

How to add a virtual column with the schema builder?

laravelmariadb

提问by mpen

I'm creating a table like this,

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

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

But I want to add one extra column. It looks like this in raw SQL:

但我想添加一个额外的列。在原始 SQL 中看起来像这样:

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

How can I add it in my migration? I will also need to create an index on it.

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

回答by Angelos Koufakis

I know this is an old question, but there is a way to do it using the schema builder since Laravel 5.3, so I thought I would put it here for completeness.

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

You can use laravel 5.3 column modifiersvirtualAs or storedAs.

您可以使用 laravel 5.3列修饰符virtualAs 或 storedAs。

So, to create a virtual generated column to be computed at every query you would create the column like this:

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

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

To create a stored generated column you would create the column like this instead:

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

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

回答by lukasgeiter

I don't think you can do it with the schema builder (someone please correct me if I'm wrong) but you can always "fall back" to raw SQL:

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

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