Laravel 的数据库迁移功能允许你通过 PHP 代码来定义和修改数据库结构,这使得数据库版本控制变得简单且团队协作更加方便。
php artisan make:migration create_table_name_table
这会在 database/migrations
目录下创建一个新的迁移文件,文件名包含时间戳和表名。
迁移文件包含 up()
和 down()
方法:
public function up()
{
Schema::create('table_name', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('table_name');
}
$table->id()
- 自增主键$table->string('name')
- VARCHAR 类型$table->text('description')
- TEXT 类型$table->integer('votes')
- INTEGER 类型$table->boolean('confirmed')
- BOOLEAN 类型$table->dateTime('created_at')
- DATETIME 类型$table->timestamps()
- 创建 created_at 和 updated_at 字段php artisan migrate
回滚最后一次迁移:
php artisan migrate:rollback
回滚所有迁移:
php artisan migrate:reset
回滚并重新运行所有迁移:
php artisan migrate:refresh
php artisan make:migration add_column_to_table_name_table --table=table_name
public function up()
{
Schema::table('table_name', function (Blueprint $table) {
$table->string('new_column')->after('existing_column');
});
}
public function down()
{
Schema::table('table_name', function (Blueprint $table) {
$table->dropColumn('new_column');
});
}
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->string('email')->unique(); // 唯一索引
$table->index('column_name'); // 普通索引
查看已运行和未运行的迁移:
php artisan migrate:status
--force
选项在生产环境运行迁移:php artisan migrate --force
通过以上方法,你可以有效地使用 Laravel 的数据库迁移功能来管理数据库结构变更。