在 Laravel 中,可以使用迁移文件中的 Schema
类来固定表。具体操作是在迁移文件中的 up()
方法中使用 create()
方法创建新表,或使用 table()
方法修改现有表,并使用 dropIfExists()
方法删除表。例如:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
这段代码会在数据库中创建一个名为 users
的表,包含 id
、name
和 timestamps
三个字段。若要修改现有表,则可以使用 table()
方法,例如:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('email')->after('name');
$table->dropColumn('password');
});
}
这段代码会向 users
表中添加一个名为 email
的字段,并删除名为 password
的字段。在以上操作中,Schema
类会自动检查表是否存在,并在必要时创建或修改它。因此,不需要手动确认表是否存在或手动执行 SQL 语句,这样可以避免错误和不必要的操作。