Laravel 迁移默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37662955/
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
Laravel migration default value
提问by nrofis
I didn't understand what is the effect of the default
option in the migrations.
我不明白default
迁移中的选项有什么影响。
I can see that the column in the database is defined with default value, but the models are ignore it completely. Say I have a Book
model that reflect the books
table in the database. I have migration to create the books table:
我可以看到数据库中的列是用默认值定义的,但模型完全忽略了它。假设我有一个Book
反映books
数据库中表的模型。我有迁移来创建书籍表:
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
->string('author');
->string('title');
->decimal('price', 4, 1)->default(100);
->timestamps();
});
When I create a new instance of Book
model I see:
当我创建Book
模型的新实例时,我看到:
$book = new Book();
var_dump($book->price); //Always 0...
The default value is ignored and the attribute is not sets correctly. Ok, I can get it, because it is a new object and it shouldn't get the default values from the DB. Butif I tries to save model like:
默认值被忽略并且属性设置不正确。好的,我可以得到它,因为它是一个新对象,它不应该从数据库中获取默认值。但是,如果我尝试保存模型,例如:
$book = new Book();
$book->author = 'Test'
$book->title = 'Test'
$book->save();
It is saves 0in the field price
in the database!
它在数据库中的字段中保存0price
!
So what is the point of the default
option in the migrations?
那么default
迁移中的选项有什么意义呢?
By the way... It wasn't be better if the model see inside the migration (if exists) what are the fields types and behavior instead to define it manually in the model and the migration? And moreover, even to create a validator automatically for the model. I think that it was possible with small change of the migration structure, so why it is not like that?
顺便说一句......如果模型在迁移内部(如果存在)看到什么是字段类型和行为,而不是在模型和迁移中手动定义它,那就更好了?此外,甚至为模型自动创建验证器。我认为迁移结构的微小变化是可能的,那么为什么不是那样呢?
回答by Khan Shahrukh
Put the default value in single quote and it will work as intended. An example of migration:
将默认值放在单引号中,它将按预期工作。迁移示例:
$table->increments('id');
$table->string('name');
$table->string('url');
$table->string('country');
$table->tinyInteger('status')->default('1');
$table->timestamps();
EDIT :in your case ->default('100.0');
编辑:在你的情况下 ->default('100.0');
回答by Rohit
You can simple put the default value using default(). See the example
您可以使用 default() 简单地放置默认值。看例子
$table->enum('is_approved', array('0','1'))->default('0');
I have used enum here and the default value is 0.
我在这里使用了枚举,默认值为 0。
回答by Tianma1970
In Laravel 6 you have to add 'change' to your migrations file as follows: $table->enum('is_approved', array('0','1'))->default('0')->change();
在 Laravel 6 中,您必须将 'change' 添加到您的迁移文件中,如下所示: $table->enum('is_approved', array('0','1'))->default('0')->change( );