php 在 Laravel 迁移中使列不可为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14013832/
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
Make column not nullable in a Laravel migration
提问by bilalq
I'm writing a migration to make certain columns in a table nullableright now. For the down function, I of course want to make those columns not nullableagain. I looked through the schema builder docs, but couldn't see a way to do this.
我正在编写迁移以立即在表中创建某些列nullable。对于向下功能,我当然想not nullable再次制作这些列。我查看了schema builder docs,但看不到这样做的方法。
Any help would be appreciated.
任何帮助,将不胜感激。
回答by TLGreg
Prior to Laravel 5 there was no Laravel native way of altering an existing table column using the schema builder. You'd need to use raw queries for this.
在 Laravel 5 之前,Laravel 没有使用模式构建器更改现有表列的本地方式。您需要为此使用原始查询。
However, as of Laravel 5 you can use:
但是,从 Laravel 5 开始,您可以使用:
$table->...->nullable(false)->change();
回答by Matt McDonald
As of Laravel 5, it's possible to reverse this natively - simply pass false as an argument to nullable().
从 Laravel 5 开始,可以在本机上反转这一点 - 只需将 false 作为参数传递给 nullable()。
e.g.
例如
$table -> string('foo') -> nullable(false) -> change();
回答by funerr
First run this:
首先运行这个:
composer require doctrine/dbal
composer require doctrine/dbal
Then create a migration that will alter the table like so:
然后创建一个将改变表的迁移,如下所示:
php artisan make:migration fix_whatever_table_name_here
php artisan make:migration fix_whatever_table_name_here
public function up()
{
Schema::table('table_name', function (Blueprint $table) {
$table->type('column')->nullable(false)->change();
});
}
public function down()
{
Schema::table('table_name', function ($table) {
$table->dropColumn('column');
});
}
回答by Gabriel Fernandez
You can just declare the column again without ->nullable() and use ->change
您可以在没有 ->nullable() 的情况下再次声明该列并使用 ->change
public function up()
{
Schema::table('table_name', function (Blueprint $table) {
$table->type('column')->change();
});
}
public function down()
{
Schema::table('table_name', function ($table) {
$table->type('column')->nullable()->change();
});
}

