我创建了一个这样的表
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`
如何将其添加到迁移中?我还需要在上面创建一个索引。
3条答案
按热度按时间oymdgrw71#
我知道这是一个老问题,但是从Laravel 5.3开始,有一种方法可以使用模式构建器来完成它,所以我想我会把它放在这里以确保完整性。
您可以使用laravel 5.3列修饰符virtualAs或storedAs。
因此,要创建一个虚拟生成列,以便在每次查询时计算,您可以像这样创建列:
要创建一个存储的生成列,您可以像这样创建列:
rdrgkggo2#
你也可以使用Laravel Events来实现相同的结果,而不使用storedAs或virtualAs。供参考:Laravel: performing some task on every insert/update when using Query Builder or Eloquent ORM
我是这样做的:
e4eetjau3#
我不认为你可以用schema builder(如果我错了,请有人纠正我)来做这件事,但你总是可以“回退到”原始SQL: