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.
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 Schema 门面提供了 创建和操作数据的支持。 它对所有Laravel支持的数据库系统分享了同样的表达法,和丰富的API 。
#建立迁移文件
To create a migration, use the make:migration
Artisan command:
使用Artisan CLI的命令 make:migration 建立迁移文件
php artisan make:migration create_users_table
<?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:
-- table 和 --create 参数 用来指定数据表名,和迁移是否要创建一个新数据表。这些选项针对特定的表简单的填写生成的基础文件
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 up
method.
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 table
method 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 yourcomposer.json
file and run thecomposer 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');