Laravel5.1学习笔记17 数据库3 数据迁移

  • 介绍
  • 创建迁移文件
  • 迁移文件结构
    • 执行迁移
    • 回滚迁移
  • 填写迁移文件 
    • 建立表
    • 重命名/ 删除表
    • 建立字段
    • 修改字段
    • 删除字段
    • 创建索引
    • 删除索引
    • 外键约束

#介绍

Migrations are like version control for your database, allowing a team to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema.php

The Laravel Schema facade provides database agnostic support for creating and manipulating tables. It shares the same expressive, fluent API across all of Laravel's supported database systems.laravel

迁移是一种数据库版本控制,可让团队在修改数据库结构的同时,保持彼此的进度一致。 迁移一般会和结构生成器一块儿使用, 能够简单的管理数据库结构。git

Laravel Schema 门面提供了 建立和操做数据的支持。 它对全部Laravel支持的数据库系统分享了一样的表达法,和丰富的API 。数据库

 

#创建迁移文件

To create a migration, use the make:migration Artisan command:express

使用Artisan CLI的命令 make:migration 创建迁移文件json

php artisan make:migration create_users_table
执行命令后,将会在项目的 database\migration目录下创建一个文件 2015_07_04_222710_create_users_table.php
<?php

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

class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}

The new migration will be placed in your database/migrations directory. Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations.数组

新的迁移文件放在database/migrations目录下, 文件名包含时间戳记,在执行迁移时用来决定顺序。 闭包

The --table and --create options may also be used to indicate the name of the table and whether the migration will be creating a new table. These options simply pre-fill the generated migration stub file with the specified table:app

-- table 和 --create 参数  用来指定数据表名,和迁移是否要建立一个新数据表。这些选项针对特定的表简单的填写生成的基础文件composer

php artisan make:migration add_votes_to_users_table --table=users

php artisan make:migration create_users_table --create=users

 

#执行迁移

A migration class contains two methods: up and down. The up method is used to add new tables, columns, or indexes to your database, while the down method should simply reverse the operations performed by the upmethod.

Within both of these methods you may use the Laravel schema builder to expressively create and modify tables. To learn about all of the methods available on the Schema builder, check out its documentation. For example, let's look at a sample migration that creates a flights table:

一个迁移类包含两个方法: up 和 down. up方法用来对数据库添加新的表,字段 或是 索引, 而down方法则是简单的对up方法的反操做。

这两个方法你可使用Laravel的Schema 构建器快速的建立和修改表。 要深刻了解Schema构建器的全部方法,请参考文档, 如今来看一个简单的例子,建立一个flights表。

<?php

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

class CreateFlightsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('flights', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('airline');
$table->timestamps();
});
}

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

 

#运行迁移

To run all outstanding migrations for your application, use the migrate Artisan command. If you are using theHomestead virtual machine, you should run this command from within your VM:

要运行全部未完成的迁移,使用migration这个Artisan命令, 若是你使用 Homestead 虚拟机, 你应该在虚拟机里面运行命令。

php artisan migrate

If you receive a "class not found" error when running migrations, try running the composer dump-autoload command and re-issuing the migrate command.

若是运行迁移时你收到“class not found”的错误,尝试运行composer dump-autoload命令,而后在从新运行migration 命令。

在生产环境强制执行迁移

Some migration operations are destructive, meaning they may cause you to lose data. In order to protect you from running these commands against your production database, you will be prompted for confirmation before these commands are executed. To force the commands to run without a prompt, use the --force flag:

有一些迁移操做是破坏性的,意味着你要丢失数据,要防止你在生产数据库运行这些命令,你会在命令执行前被提示确认,要忽略提示强制执行这些命令,使用—force选项。

php artisan migrate --force

回滚迁移

To rollback the latest migration "operation", you may use the rollback command. Note that this rolls back the last "batch" of migrations that ran, which may include multiple migration files:

要回滚上一次迁移,你可使用rollback命令,注意这会回滚上次的运行的批量迁移,你能够包括多个迁移文件。

php artisan migrate:rollback

The migrate:reset command will roll back all of your application's migrations:

而 migrate:reset 命令会回滚你全部应用的迁移

php artisan migrate:reset

在一条命令中回滚、迁移

The migrate:refresh command will first roll back all of your database migrations, and then run the migrate command. This command effectively re-creates your entire database:

migrate:refresh命令首先回滚全部的数据据迁移, 而后运行migrate 命令, 这个命令有效地重建了整个数据库。

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

#编写迁移文件

建立表

To create a new database table, use the create method on the Schema facade. The create method accepts two arguments. The first is the name of the table, while the second is a Closure which receives a Blueprint object used to define the new table:

建立新的数据库表,使用Schema 门面的 create方法,这个create方法接受两个引数。 第一个是表名, 第二个是一个闭包函数,接收一个Blueprint对象来定义表。

Schema::create('users', function ($table) {
$table->increments('id');
});

Of course, when creating the table, you may use any of the schema builder's column methods to define the table's columns.

固然,当建立表的时候,你可以使用Schema构造器中的 column 方法去定义这个表的字段。

检查表和字段存在与否

You may easily check for the existence of a table or column using the hasTable and hasColumn methods:

你能够很容易查看表和字段是否存在,分别使用 hasTable 和 hasColumn 方法

if (Schema::hasTable('users')) {
//
}

if (Schema::hasColumn('users', 'email')) {
//
}

链接和存储引擎

If you want to perform a schema operation on a database connection that is not your default connection, use theconnection method:

若是你想在一个不是默认数据库链接上执行一个数据库结构(Schema)操做,使用connection方法。

Schema::connection('foo')->create('users', function ($table) {
$table->increments('id');
});

To set the storage engine for a table, set the engine property on the schema builder:

设置一个表的存储引擎,经过在schema构建器设置engine属性来达到。

Schema::create('users', function ($table) {
$table->engine = 'InnoDB';

$table->increments('id');
});

重命名和删除表

To rename an existing database table, use the rename method:

使用rename方法来重命名一个已经存在的数据表。

Schema::rename($from, $to);

To drop an existing table, you may use the drop or dropIfExists methods:

使用drop 或dropIfExists方法来删除一个已经存在的表。

Schema::drop('users');

Schema::dropIfExists('users');

建立字段

To update an existing table, we will use the table method on the Schema facade. Like the create method, the tablemethod accepts two arguments: the name of the table and a Closure that receives a Blueprint instance we can use to add columns to the table:

要更新已经存在的表,咱们在Schema门面使用table方法,就像create方法,table方法接受两个引数, 表名称, 和闭包函数接受一个Blueprint对象, 可使用它来添加字段。

Schema::table('users', function ($table) {
$table->string('email');
});
容许存在的字段类型

Of course, the schema builder contains a variety of column types that you may use when building your tables:

固然,Schema构建器包含一系列字段类型,你能够用来创建表结构。

命令 描述
$table –>bigIncrements(‘id’); Incrementing ID using a “big integer” equivalent.
$table->bigInteger(‘votes’); BIGINT equivalent for the database.
$table->binary(‘data’); BLOB equivalent for the database.
$table->boolean(‘confirmed’); BOOLEAN equivalent for the database.
$table->char(‘name’,4) CHAR equivalent with a length
$table->date(‘create_at’); DATE equivalent for the database.
$table->dateTime(‘create_at’); DATETIME equivalent for the database.
$table->decimal(‘amount’,5,2); DECIMAL equivalent with a precision and scale.
$table->double(‘column’,15,8); DOUBLE equivalent with precision, 15 digits in total and 8 after the decimal point.
$table->enum(‘choices’,[‘foo’, ‘bar’]); ENUM equivalent for the database.
$table->float(‘amount’); FLOAT equivalent for the database.
$table->increments(‘id’); Incrementing ID for the database(primary key).
$table->integer(‘votes’); INTEGER equivalent for the database.
$table->json(‘options’); JSON equivalent for the database.
$table->jsonb(‘option’); JSONB equivalent for the database.
$table->longText(‘description’); LONGTEXT equivalent for the database.
$table->mediumInteger(‘numbers’); MEDIUMINT equivalent for the database.
$table->mediumText(‘description’); MEDIUMTEXT equivalent for the database.
$table->morphs(‘taggable’); Adds INTEGER taggable_id and STRING taggable_type.
$table->nullableTimestamps(); Same as timestamps(), except allows NULLs.
$table->rememberToken(); Adds remember_token as VARCHAR(100) NULL
$table->smallInteger(‘votes’); SMALLINT equivalent for the database.
$table->softDeletes(); Adds deleted_at column for soft deletes.
$table->string(‘email’); VARCHAR equivalent column
$table->string(‘name’, 100); VARCHAR equivalent with a length
$table->text(‘description’); TEXT equivalent for the database.
$table->time(‘sunrise’); TIME equivalent for the database.
$table->tinyInteger(‘numbers’); TINYINT equivalent for the database.
$table->timestamp(‘added_on’); TIMESTAMP equivalent for the database.
$table->timestamps(); Adds created_at and updated_at columns.
 
 

字段修改器

In addition to the column types listed above, there are several other column "modifiers" which you may use while adding the column. For example, to make the column "nullable", you may use the nullable method:

在以上的字段类型以外,还有其余几个字段的“修改器”, 当你添加字段的时候可能会用,例如,要是要使一个字段变成”nullable“,你可使用nullable 方法:

Schema::table('users', function ($table) {
$table->string('email')->nullable();
});

Below is a list of all the available column modifiers. This list does not include the index modifiers:

如下是全部可用的字段修改器,不包括index修改器。

修改器 描述
->first() Place the column “first” in the table(MySQL Only)
->after(‘column’) Place the column ‘after’ another column (MySQL Only)
->nullable() Allow NULL values to be inserted into the column
->default($value) Specify a “default”value for the column
->unsigned() Set integer columns to UNSIGNED

 
 

#修改字段

属性

Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column.

在修改字段以前,确认已经把 doctrine/dbal 依赖加入到你的composer.json文件,这个 Doctrine DBAL库,是用来决定字段的如今状态,和建立实现指定修改所需的SQL查询。

更新字段的属性

The change method allows you to modify an existing column to a new type, or modify the column's attributes. For example, you may wish to increase the size of a string column. To see the change method in action, let's increase the size of the name column from 25 to 50:

change 方法容许你改变一个已存在的字段到新的类型,或者修改字段的属性,例如,你可能但愿增长字符串字段的尺寸。要看看change方法的使用,咱们把name 字段的尺寸从25增长到50:

Schema::table('users', function ($table) {
$table->string('name', 50)->change();
});

咱们也能够修改一个字段成为 nullable :

Schema::table('users', function ($table) {
$table->string('name', 50)->nullable()->change();
});

字段更名

To rename a column, you may use the renameColumn method on the Schema builder. Before renaming a column, be sure to add the doctrine/dbal dependency to your composer.json file:

要重命名一个字段,在Schema构建器里,你可使用 renameColumn 方法。 在重命名字段以前,要确认增长 doctrine/dbal依赖到composer.json文件里。

Schema::table('users', function ($table) {
$table->renameColumn('from', 'to');
});

Note: 在表里对enum 字段 更名称如今还不被支持.

 

删除字段

To drop a column, use the dropColumn method on the Schema builder:

要删除字段,在Schema构建器里使用dropColumn方法

Schema::table('users', function ($table) {
$table->dropColumn('votes');
});

You may drop multiple columns from a table by passing an array of column names to the dropColumn method:

你可能要在一个表里删除多个字段,经过在dropColumn方法里传入字段名字的数组来达成。

Schema::table('users', function ($table) {
$table->dropColumn(['votes', 'avatar', 'location']);
});

Note: Before dropping columns from a SQLite database, you will need to add the doctrine/dbal dependency to your composer.json file and run the composer update command in your terminal to install the library.

 

建立索引

The schema builder supports several types of indexes. First, let's look at an example that specifies a column's values should be unique. To create the index, we can simply chain the unique method onto the column definition:

schema构建器支持几种类型的索引,首先让咱们看一个例子,指定一个字段的值须惟一。 要建立这样的索引,咱们只要简单在column定义后连接unique方法。

$table->string('email')->unique();

Alternatively, you may create the index after defining the column. For example:

另外一种途径,你能够在定义字段以后,创建索引

$table->unique('email');

You may even pass an array of columns to an index method to create a compound index:

你更能够传入一个字段的数组到index方法来建立一个复杂索引

$table->index(['account_id', 'created_at']);

可使用的索引类型

方法 描述
$table->primary(‘id’); 增长一个主键
$table->primary(‘first’, ‘last’) 增长一个复合键
$table->unique(‘email’); 增长一个惟一索引
$table->index(‘state’); 增长一个基本索引

删除索引

To drop an index, you must specify the index's name. By default, Laravel automatically assigns a reasonable name to the indexes. Simply concatenate the table name, the names of the column in the index, and the index type. Here are some examples:

删除一个索引,你必须指定索引的名字,默认,Laravel会自动指定一个合理的名字到给索引,只简单地把表名,索引所在的字段名,和索引类型链接在一块儿,这是例子。

方法 描述
$table->dropPrimary(‘users_id_primary’); 从users表删除主键
$table->dropUnique(‘users_email_unique’); 从users表删除惟一索引
$table->dropIndex(‘geo_state_index’); 从geo表删除基本索引

外键束缚

Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user_id column on the posts table that references the id column on ausers table:

Laravel也提供了对外键束缚的支持,用来保证数据库级别的参照完整性,例如,让咱们在posts表定义要给user_id 字段,参照users表的id字段。

Schema::table('posts', function ($table) {
$table->integer('user_id')->unsigned();

$table->foreign('user_id')->references('id')->on('users');
});

You may also specify the desired action for the "on delete" and "on update" properties of the constraint:

你也能够制定约束的”on delete”和”on update”属性对应的动做

$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');

To drop a foreign key, you may use the dropForeign method. Foreign key constraints use the same naming convention as indexes. So, we will concatenate the table name and the columns in the constraint then suffix the name with "_foreign":

要删除一个外键,你可使用dropForeign方法,外键束缚使用和索引相同的命名规范, 咱们只要连接束缚中的表名和字段名而后结尾加上”_foreign”:

$table->dropForeign('posts_user_id_foreign');
相关文章
相关标签/搜索