我可以在Laravel中自动创建数据库表,如Django的'python manage syncdb'吗?

Raj*_*ena 0 php django syncdb laravel

我从Django的(Python)的背景和这几天我正在一个项目来了这是基于Laravel(PHP).做我有一个自动生成数据库表中的一些选项?

Nil*_*ner 7

是的,使用Schema BuilderMigrations.

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

$ php artisan migrate:install
Run Code Online (Sandbox Code Playgroud)

然后创建一个迁移

$ php artisan migrate:make create_users_table
Run Code Online (Sandbox Code Playgroud)

这将创建一个PHP文件application/migrations.您现在可以对其进行编辑以获得所需的设置,即

<?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');
    }

}
Run Code Online (Sandbox Code Playgroud)

并使用.执行它

$ php artisan migrate
Run Code Online (Sandbox Code Playgroud)

每次更改数据库结构时,都必须创建新的迁移并在之后执行.

假设您想要users一个新列,hometown而不是phone创建一个新的迁移

$ php artistan migrate:make users_table_add_hometown
Run Code Online (Sandbox Code Playgroud)

并编辑要包含的新文件

<?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');
        });
    }

}
Run Code Online (Sandbox Code Playgroud)

您现在有两个迁移,一个创建表,另一个修改它.

artisan migrate命令足够智能,只能执行系统新增的迁移.因此,如果你的同事在长假后回家并且有一些新的迁移,它将自动只导入他离开后创建的那些.