在 Laravel 中,数据库迁移和数据填充是一种非常方便的方式来管理数据库结构和插入初始数据。以下是如何使用 Laravel 数据库迁移和数据填充的步骤:
1. 创建迁移文件
首先,你需要创建一个迁移文件来定义数据库表结构。你可以使用 Artisan 命令行工具来创建迁移文件:
php artisan make:migration create_users_table --create=users
这将会创建一个名为 create_users_table
的迁移文件,通常位于 database/migrations
目录下。
2. 编辑迁移文件
打开迁移文件并定义表结构。例如:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration {
/** * Run the migrations. * * @return void */
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();
});
}
/** * Reverse the migrations. * * @return void */
public function down() {
Schema::dropIfExists('users');
}
}
3. 运行迁移
接下来,你需要运行迁移来创建表结构:
php artisan migrate
4. 创建数据填充文件
你可以使用 Artisan 命令行工具来创建一个数据填充文件:
php artisan make:seeder UsersTableSeeder
这将会创建一个名为 UsersTableSeeder
的数据填充文件,通常位于 database/seeders
目录下。
5. 编辑数据填充文件
打开数据填充文件并定义要插入的数据。例如:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\User;
class UsersTableSeeder extends Seeder {
/** * Seed the application's database. * * @return void */
public function run() {
// 让模型工厂创建一些用户
User::factory(10)->create();
}
}
6. 运行数据填充
最后,你需要运行数据填充来插入初始数据:
php artisan db:seed
总结
通过以上步骤,你已经成功创建了一个数据库迁移文件来定义表结构,并使用数据填充文件插入了初始数据。你可以根据需要重复这些步骤来管理数据库结构和插入更多数据。