迁移是数据库的一种版本控制。它们允许团队修改数据库模式并及时了解当前模式状态。迁移通常与 Schema Builder 配对以轻松管理应用程序的架构。
有了迁移,你不需要在 phpMyAdmin 中创建表,你可以在 Laravel 中完成。下面是一个创建用户表的例子:
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id'); // autoincrement id field
$table->string('name'); // string field
$table->string('lastname');
$table->string('title');
$table->string('email')->unique(); // unique string field
$table->string('password', 60); // string field with max 60 characters
$table->boolean('Status')->default(0); // string field with default value 0
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
在这段代码中,我们创建了带有“name”、“lastname”等字段的表......我们在 Laravel 代码中说过,迁移完成后它们是字符串类型,我们在数据库中有完整的带有这些字段的表。
运行迁移以创建表
要创建迁移,您可以在 Artisan CLI(artisan 命令行界面)上使用 make:migration 命令:
php artisan make:migration create_users_table
或
php artisan make:migration create_users_table --create=users
运行迁移以更改表
当您需要对数据库表进行一些更改时,例如:向用户表添加字段投票,您可以在 Laravel 代码中这样做,而无需触及 SQL 代码
php artisan make:migration add_votes_to_users_table --table=users
回滚上次迁移操作
如果您犯了错误并做错了什么,您可以随时回滚以将数据库返回到以前的状态。
php artisan migrate:rollback
回滚所有迁移
php artisan migrate:reset
回滚所有迁移并再次运行它们
php artisan migrate:refresh
php artisan migrate:refresh --seed
迁移的最大优势之一是无需接触 SQL 代码即可创建数据库。您可以在 PHP 代码中创建具有关系的整个数据库,然后将其迁移到 MySQL、PL/SQL、MSSQL 或任何其他数据库中。
另外我推荐免费的Laravel 5 fundamental series,在第 7 集中你可以听到更多关于迁移的信息。