我不明白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 稍微改变一下就可以了,为什么不是这样呢?