Laravel迁移更改并使列为空 [英] Laravel migration change and make column nullable
问题描述
我创建了一个具有user_id unsigned的迁移。如何在新的联盟中编辑user_id以使其成为 nullable()
?
I created a migration with user_id unsigned. How can I edit user_id in a new migation to also make it nullable()
?
Schema::create('throttle', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned(); // this needs to also be nullable, how should the next migration be?
}
推荐答案
我假设您正在编辑已经添加了数据的列,因此删除列并再次添加为可空列不可能没有丢失数据,我们将 alter
现有的列。
I assume that you're trying to edit a column that you have already added data on, so dropping column and adding again as a nullable column is not possible without losing data. We'll alter
the existing column.
然而,Laravel的模式构建器不支持修改列,而不是重命名列
所以你需要运行原始查询来执行,如下所示:
However, Laravel's schema builder does not support modifying columns other than renaming the column. So you will need to run raw queries to do them, like this:
function up()
{
DB::statement('ALTER TABLE `throttle` MODIFY `user_id` INTEGER UNSIGNED NULL;');
}
为确保您仍可以回滚迁移,我们将执行 down()
。
And to make sure you can still rollback your migration, we'll do the down()
as well.
function down()
{
DB::statement('ALTER TABLE `throttle` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
}
一个注意事项是,由于您在可空和不可空转换之间,需要确保在迁移之前/之后清理数据。这样做在您的迁移脚本中有两种方式:
One note is that since you are converting between nullable and not nullable, you'll need to make sure you clean up data before/after your migration. So do that in your migration script both ways:
function up()
{
DB::statement('ALTER TABLE `throttle` MODIFY `user_id` INTEGER UNSIGNED NULL;');
DB::statement('UPDATE `throttle` SET `user_id` = NULL WHERE `user_id` = 0;');
}
function down()
{
DB::statement('UPDATE `throttle` SET `user_id` = 0 WHERE `user_id` IS NULL;');
DB::statement('ALTER TABLE `throttle` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
}
这篇关于Laravel迁移更改并使列为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!