laravel 数据库迁移
时间: 2023-08-09 20:05:38 浏览: 58
Laravel 的数据库迁移(Database Migration)是一种方便的方式,可以让你通过编程的方式来管理数据库的变化,而不是通过手动 SQL 脚本来实现。
下面是 Laravel 数据库迁移的基本使用方法:
1. 创建一个新的迁移文件,可以使用 Artisan 命令 `make:migration` 来创建。例如,创建一个名为 `create_users_table` 的迁移文件,可以使用以下命令:
```
php artisan make:migration create_users_table
```
2. 打开创建的迁移文件,在 `up` 方法中编写数据库表的创建语句,例如:
```
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
```
3. 在 `down` 方法中编写数据库表的删除语句,例如:
```
public function down()
{
Schema::dropIfExists('users');
}
```
4. 运行迁移命令 `migrate`,将创建的迁移文件应用到数据库中:
```
php artisan migrate
```
如果需要回滚迁移,可以使用 `rollback` 命令:
```
php artisan migrate:rollback
```
如果需要回滚所有迁移,可以使用 `reset` 命令:
```
php artisan migrate:reset
```
以上是 Laravel 数据库迁移的基本使用方法,通过迁移文件,可以方便地管理数据库的变化,避免手动操作数据库的繁琐和出错。