问题
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?
回答1:
Yes, using the Schema Builder and Migrations.
First you need to install the migrations table to the DB:
$ php artisan migrate:install
then create a migration
$ php artisan migrate:make create_users_table
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');
}
}
and execute it using
$ php artisan migrate
Every time you change the database structure you'll have to create a new migration and execute it afterwards.
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
and edit the new file to contain
<?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.
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.
来源:https://stackoverflow.com/questions/16123888/can-i-create-database-tables-automatically-in-laravel-like-djangos-python-mana