我不明白default选项在迁移中有什么影响.

我可以看到数据库中的列是用默认值定义的,但是模型完全忽略了它.假设我有一个反映数据库中books表的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 = 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();

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

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

顺便说一下... 如果模型看到迁移内部(如果存在),那么在模型和迁移中手动定义它的字段类型和行为是什么?此外,甚至为模型自动创建验证器.我觉得移民 struct 稍微改变一下就可以了,为什么不是这样呢?

推荐答案

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

Laravel相关问答推荐

到查询构建器的MySQL查询

Inertiajs - 使用链接组件添加记录但无法在不使用表单的情况下清除文本区域

Laravel:BelongstoMany 关系实现

Laravel 5.2 无法打开 laravel.log

Laravel 5文件夹 struct 中的文件保存在哪里?

.gitignore 不忽略文件夹

Laravel:如何在没有数据库的情况下对用户进行身份验证

Laravel 4 定义 RESTful 控制器

从 Laravel Cashier 获取下一个账单日期

Laravel 将参数从路由传递到过滤器

Laravel - 自定义时间戳列名称

如何在 Laravel Eloquent 中 Select 某些字段?

Laravel 存储文件的公共 url

Filesystem.php 中的 ErrorException

Laravel 项目旁边的 Wordpress 项目(在 public_html 文件夹中)

如何在不使用视图的情况下使用 Laravel 4 发送Electron邮件?

在 Laravel 4 中使用 HTML 占位符

Laravel 5 - 从控制器级别的所有请求对象中删除参数

Laravel 仓库

Laravel 中的 isDirty() 是什么意思?