我来自 Django(Python) 背景,这些天我正在开发一个基于 Laravel(PHP) 的项目。我有一些选项,比如自动生成数据库表吗?
问问题
4329 次
1 回答
8
是的,使用Schema Builder和Migrations。
首先,您需要将迁移表安装到数据库:
$ php artisan migrate:install
然后创建迁移
$ php artisan migrate:make create_users_table
这将在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');
}
}
并使用执行它
$ 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
命令足够聪明,只执行系统新的迁移。因此,如果您的一位同事在长假后回家并且有一些新的迁移,它会自动只导入他离开后创建的迁移。
于 2013-04-20T19:02:53.620 回答