Laravel 5.2数据库--迁移migration

时间:2023-03-08 21:32:36

   Laravel中的migrations文件存放的是数据库表文件等结构,可以说是一个跟git差不多的,可以说像是数据库的版本控制器,所以可以叫做迁移。因为它可以很快速的很容易地构建应用的数据库表结构。

  1. 生成迁移

  使用 Artisan 命令make:migration来创建一个新的迁移:

 php artisan make:migration create_users_table

  就会在database/migrations目录下生成新的迁移文件,而已名称都是包含时间戳,因此预先laravel判断其顺序。

2.迁移文件的目录结构

  里面包含了两个方法:updownup方法用于新增表,列或者索引到数据库,而down方法就是up方法的反操作,和up里的操作相反。

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration; class CreateFlightsTable extends Migration{
/**
* 运行迁移
*
* @return void
*/
public function up()
{
Schema::create('flights', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('airline');
$table->timestamps();
});
} /**
* 撤销迁移
*
* @return void
*/
public function down()
{
Schema::drop('flights');
}
}

    3.进行文件迁移

php artisan migrate 

    4、迁移回滚

    想要回滚最新的一次迁移”操作“,可以使用rollback命令,注意这将会回滚最后一批运行的迁移,可能包含多个迁移文件:

php artisan migrate:rollback

    migrate:reset命令将会回滚所有的应用迁移:

php artisan migrate:reset

    migrate:refresh命令将会先回滚所有数据库迁移,然后运行migrate命令。这个命令可以有效的重建整个数据库:

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

    在up方法里面创建列的时候,发现想要用varchar字符类型找不到,原来laravel的varchar类型变成了string()方法了,在用的时候:

$table->string('name', 100);   //等同于数据库中的 VARCHAR,带一个长度

  

    二、创建索引

  1、一般可用索引类型有:主键索引、混合索引、唯一索引、自定义索引名称、普通索引。

命令 描述
$table->primary('id'); 添加主键索引
$table->primary(['first', 'last']); 添加混合索引
$table->unique('email'); 添加唯一索引
$table->unique('state', 'my_index_name'); 指定自定义索引名称
$table->index('state'); 添加普通索引
命令 描述
$table->dropPrimary('users_id_primary'); 从 “users”表中删除主键索引
$table->dropUnique('users_email_unique'); 从 “users”表中删除唯一索引
$table->dropIndex('geo_state_index'); 从 “geo”表中删除普通索引

  出错误问题:

[Symfony\Component\Debug\Exception\FatalThrowableError]

Call to a member function comment() on null

出现这个问题的原因是我在添加列$table->timestamps();时间戳的时候,后面链式调用了注释方法$table->timestamps()->comment('时间');

这是由于$table->timestamps();这个timestamps()方法里面是没有return  $this; 的结果导致的。