我可以像Django's 'python manage syncdb'一样在Laravel中自动


Can I create database tables automatically in Laravel like Django's 'python manage syncdb'?

我来自Django(Python)背景,这些天我正在做一个基于Laravel(PHP)的项目。我有一些选项,如自动生成数据库表?

是的,使用架构构建器和迁移。

首先需要将迁移表安装到DB:

$ 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命令非常智能,可以只执行系统中的新迁移。因此,如果您的一位同事在长假后回家,并且有一些新的迁移,它将自动只导入在他离开后创建的那些。