我来自Django(Python)背景,如今我正在基于Laravel(PHP)的项目中工作。我是否可以选择一些选项,例如自动生成数据库表?
是,使用Schema Builder和Migrations。
首先您需要将迁移表安装到数据库:
$ php artisan migrate:install
然后创建迁移
$ php artisan migrate:make create_users_table
这将在application/migrations
中创建一个PHP文件。您现在可以对其进行编辑以具有所需的设置,即
<?php
class Create_Users_Table
{
public function up()
{
Schema::create('users', function($table)
{
$table->increments('id');
$table->string('username');
$table->string('email');
$table->string('phone')->nullable();
$table->text('about');
$table->timestamps();
});
}
public function down()
{
Schema::drop('users');
}
}
并使用]执行>
$ php artisan migrate
每次更改数据库结构时,都必须创建一个新的迁移并在之后执行它。
说您希望users
有一个新列hometown
而不是phone
,您将创建一个新的迁移
$ php artistan migrate:make users_table_add_hometown
并编辑要包含的新文件
<?php class Users_Table_Add_Hometown { public function up() { Schema::table('users', function($table) { $table->string('hometown'); $table->drop_column('phone'); }); } public function down() { Schema::table('users', function($table) { $table->string('phone')->nullable(); $table->drop_column('hometown'); }); } }
您现在有两个迁移,一个创建表,另一个修改表。
artisan migrate
命令足够聪明,仅可以执行系统新的迁移。因此,如果您的同事在长假后回家并且有一些新的迁移,它将仅自动导入他离开后创建的迁移。
您可以添加命令来帮助您创建新安装的数据库。请参考link