How to add a virtual column with the schema builder?

倖福魔咒の 提交于 2020-01-02 04:37:09

问题


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:

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.


回答1:


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.

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



回答2:


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:

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


来源:https://stackoverflow.com/questions/27749887/how-to-add-a-virtual-column-with-the-schema-builder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!