如何使用架构生成器添加虚拟列? [英] How to add a virtual column with the schema builder?
问题描述
我正在创建一个这样的表,
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');
});
但是我想增加一列.在原始SQL中看起来像这样:
But I want to add one extra column. It looks like this in raw 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.
推荐答案
我知道这是一个老问题,但是自Laravel 5.3起,就有一种方法可以使用架构生成器来实现,所以我想将其放在此处完整性.
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 列修饰符 virtualAs或storedAs.
You can use laravel 5.3 column modifiers virtualAs or 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)' );
这篇关于如何使用架构生成器添加虚拟列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!