是否可以像Django的"python manage syncdb"一样在Laravel中自动创建数据库表?
我来自Django(Python),如今我正在一个基于Laravel(PHP)的项目中.我是否可以选择一些选项,例如自动生成数据库表?
I came from Django(Python) background and these days I'm working on a project which is based on Laravel(PHP).Do I have some option like generating database tables automatically?
是的,使用 Schema Builder 和迁移.
首先,您需要将迁移表安装到数据库:
First you need to install the migrations table to the DB:
$ php artisan migrate:install
然后创建迁移
$ php artisan migrate:make create_users_table
这将在application/migrations
中创建一个PHP文件.您现在可以对其进行编辑以具有所需的设置,即
this will create a PHP file in application/migrations
. You may now edit it to have the settings you want, i.e.
<?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
每次更改数据库结构时,都必须创建一个新迁移,然后再执行它.
Every time you change the database structure you'll have to create a new migration and execute it afterwards.
假设您希望users
拥有一个新列hometown
而不是phone
,您将创建一个新的迁移
Say you want users
to have a new column hometown
instead of phone
you'd create a new migration
$ 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');
});
}
}
您现在有两次迁移,一次创建表,另一次修改表.
You now have two migrations, one creating the table and one modifying it.
artisan migrate
命令非常聪明,仅可以执行系统新的迁移.因此,如果您的同事在长假后回家,并且有一些新的迁移,它将自动仅导入他离开后创建的迁移.
The artisan migrate
command is smart enough to only execute migrations that are new to the system. So if a collegue of yours comes home after a long vacation and there were a few new migrations it will automatically only import the ones that were created after he left.