数据库迁移
数据库迁移
数据库迁移就像是数据库的版本控制,可以让你的团队轻松修改并共享应用程序的数据库结构。迁移通常会搭配上 Laravel 的数据库结构构造器来让你方便地构建数据库结构。如果你曾经出现过让同事手动在数据库结构中添加字段的情况,数据库迁移可以解决你这个问题。
假设需要建的表结构为:
CREATE TABLE IF NOT EXISTS students(
`id` INT AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '姓名',
`age` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '年龄',
`sex` INT UNSIGNED NOT NULL DEFAULT 10 COMMENT '性别',
`create_at` INT UNSIGNED NOT NULL DEFAULT 10 COMMENT '新增时间',
`update_at` INT UNSIGNED NOT NULL DEFAULT 10 COMMENT '修改时间'
) ENGINE=InnoDB DEFAULT CHARSET utf8
AUTO_INCREMENT=1001 COMMENT='学生表';
方式1: 新建一个students 表的迁移文件
$ php artisan make:migration create_students_table
-- table 和 --create参数可以用来指定数据表的名称,以及迁移文件是否要建立新的数据表
实际操作步骤
执行一下命令
$ php artisan make:migration create_students_table --create=students
database/migrations/ 目录下则会创建2016_08_26_104514_create_students_table.php 文件
修改文件中的up函数
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('age')->unsigned()->default(0);
$table->integer('sex')->unsigned()->default(10);
$table->integer('created_at')->default(0);
$table->integer('updated_at')->default(0);
});
}
执行以下命令,完成数据表的构建:
php artisan migration
方式2:生成模型的同时生成迁移文件
$ php artisan make:model Student -m
实际操作步骤:
$ php artisan make:model Article -m
database/migrations/ 目录下则会创建2016_08_26_104605_create_articles_table.php文件,相应的模型文件(app/Article.php)也被创建了
执行以下命令,完成数据表的构建:
php artisan migration
Last updated
Was this helpful?