是否可以像Django的"python manage syncdb"一样在Laravel中自动创建数据库表? [英] Can I create database tables automatically in Laravel like Django's 'python manage syncdb'?

查看:108
本文介绍了是否可以像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.

这篇关于是否可以像Django的"python manage syncdb"一样在Laravel中自动创建数据库表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆