您的位置:首页 > 编程语言 > PHP开发

Laravel 5.2 教程 - 迁移

2016-08-17 16:57 405 查看

一、简介

迁移(Migrations)是一种数据库的版本控制。可以让团队在修改数据库结构的同时,保持彼此的进度一致。迁移通常会和 结构生成器 一起使用,可以简单的管理数据库结构。

下面以创建学生表的迁移为例,来介绍Laravel中迁移的使用。(点击查看演示数据表结构

二、建立迁移文件

1. 使用Artisan的 make:migration 命令生成students表的迁移文件

1)生成一个最基本的迁移文件:

php artisan make:migration create_students_table


迁移文件在database/migrations目录下,打开该目录你将会看见以当前年月日开头名为create_students_table的php文件。

2)如果生成的迁移文件中想带有表名,可以加上–table参数:

php artisan make:migration create_students_table --table=students


3)如果生成的迁移文件中想带有表名及基本的表字段,可以加上–create参数:

php artisan make:migration create_students_table --create=students


4)生成模型的同时,如果想生成对应的迁移文件,只需要加上-m参数即可,迁移文件中的表名默认是模型的复数形式,如果不符合自己的需要,手动更改表名即可:

php artisan make:model Student -m


该条命令将会生成 Studnet.php 模型以及2016_07_30_052127_create_students_table.php 迁移文件。

2. 结构生成器 (Schema)

打开该文件后,有一个CreateStudentsTable的类,里面有up()和down()两个方法,up方法用于生成数据表,down方法用于删除数据表。按照数据表结构,完善后该类代码如下:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStudentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('age')->unsigned();
$table->integer('sex')->unsigned()->default(10);
$table->integer('created_at');
$table->integer('updated_at');
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('students');
}
}


三、执行迁移

在控制台执行以下命令,即可执行迁移文件,生成或更新相应的表。

php artisan migrate


四、回滚迁移

1. 回滚上一次的迁移

php artisan migrate:rollback


2. 回滚所有迁移

php artisan migrate:reset


3. 回滚所有迁移并且再执行一次

php artisan migrate:refresh
php artisan migrate:refresh --seed


交友互动:

本文首发于马燕龙个人博客,欢迎分享,转载请标明出处。

马燕龙个人博客:http://www.mayanlong.com

马燕龙个人微博:http://weibo.com/imayanlong

马燕龙Github主页:https://github.com/yanlongma
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Laravel