我是否可以像Django的'python manage syncdb'一样在Laravel中自动创建数据库表?

问题描述 投票:0回答:1

我来自Django(Python)背景,如今我正在基于Laravel(PHP)的项目中工作。我是否可以选择一些选项,例如自动生成数据库表?

php django laravel syncdb
1个回答
7
投票

是,使用Schema BuilderMigrations

首先您需要将迁移表安装到数据库:

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


0
投票

您可以添加命令来帮助您创建新安装的数据库。请参考link

© www.soinside.com 2019 - 2024. All rights reserved.