Laravel迁移默认值 [英] Laravel migration default value

查看:604
本文介绍了Laravel迁移默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不了解default选项在迁移中的作用.

I didn't understand what is the effect of the default option in the migrations.

我可以看到数据库中的列是使用默认值定义的,但是模型完全忽略了它.假设我有一个Book模型,该模型反映了数据库中的books表.我已经进行迁移以创建books表:

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:

Schema::create('books', function (Blueprint $table) {
    $table->increments('id');
          ->string('author');
          ->string('title');
          ->decimal('price', 4, 1)->default(100);
          ->timestamps();
});

当我创建Book模型的新实例时,我看到:

When I create a new instance of Book model I see:

$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. But if I tries to save model like:

$book = new Book();
$book->author = 'Test'
$book->title = 'Test'
$book->save();

它将在数据库的price字段中保存 0

It is saves 0 in the field price in the database!

那么在迁移中default选项的意义是什么?

So what is the point of the default option in the migrations?

顺便说一句... 如果模型在迁移内部看到(如果存在),那不是什么更好的选择,而是在模型和迁移中手动定义字段类型和行为是什么?而且,甚至可以自动为模型创建一个验证器.我认为迁移结构的微小变化是有可能的,那为什么不这样呢?

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?

推荐答案

将默认值放在单引号中,它将按预期运行.迁移示例:

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

-根据您的情况-> default('100.0');

EDIT : in your case ->default('100.0');

这篇关于Laravel迁移默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆