[Laravel5.2 documentation] database -- migration

Source: Internet
Author: User
[Laravel5.2 documentation] database -- migration 1. Introduction

Migration is like database version control, allowing the team to easily edit and share the database table structure of the application, migration is usually paired with the Laravel schema builder to easily build the database table structure of the application.

Laravel's Schema facade provides support for creating and manipulating tables unrelated to the database system, and provides consistent, elegant, and smooth APIs in all database systems supported by Laravel.

2. generate migration

Use the Artisan command make: migration to create a new migration:

php artisan make:migration create_users_table

The new migration is located in the database/migrations directory, and each migration file name contains a timestamp, allowing Laravel to determine its order.

The -- table and -- create options can be used to specify the table name and whether to create a new data table for the migration. These options only need to be placed after the preceding migration command and specify the table name:

php artisan make:migration add_votes_to_users_table --table=usersphp artisan make:migration create_users_table --create=users

If you want to specify the custom output path for migration generation, you can use the -- path option when executing the make: migration command. the provided path should be relative to the application root directory.

3. migration structure

The migration class contains two methods: up and down. The up method is used to add tables, columns, or indexes to the database. the down method is the reverse operation of the up method, which is opposite to the operation in the up method.

You need to use the Laravel table schema builder to create and modify tables in both methods. for example, let's take a look at a simple example of creating a flights table:

 Increments ('id'); $ table-> string ('name'); $ table-> string ('airline '); $ table-> timestamps () ;};}/***** undo migration ** @ return void */public function down () {Schema :: drop ('flights ');}}
4. run migration

To run all unexecuted migration tasks in the application, you can use the migrate method of the Artisan command. If you are using the Homestead VM, you should run the following command in your VM:

php artisan migrate

If you encounter a "class not found" error when running the migration command again, try to run the composer dump-autoload command and then run the migration command again.

Force run migration in the production environment

Some migration operations are devastating, which means they may cause data loss. to avoid running these commands in the production environment database, you will be prompted and confirmed before running these commands. To forcibly run these commands without being prompted, you can use -- force:

php artisan migrate --force
Rollback migration

To roll back the latest migration "operation", you can use the rollback command. Note that this will roll back the last batch of running migration, which may contain multiple migration files:

php artisan migrate:rollback

The migrate: reset command will roll back all applications for migration:

php artisan migrate:reset
Rollback/migration in a single command

Migrate: the refresh command first rolls back all databases for migration, and then runs the migrate command. This command can effectively reconstruct the entire database:

php artisan migrate:refreshphp artisan migrate:refresh --seed
5. write a migration table

Use the create method on the Schema facade to create a new data table. The create method receives two parameters. The first is the table name, and the second is to obtain the closure of the Blueprint object used to define the new table:

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

Of course, when creating a new table, you can use any column method in the table structure builder to define the columns of the data table.

Check whether a table or column exists

You can easily use the hasTable and hasColumn methods to check whether a table or column exists:

if (Schema::hasTable('users')) {    //}if (Schema::hasColumn('users', 'email')) {    //}
Connection & Storage Engine

If you want to perform table structure operations on a database connection, the database connection is not the default database connection. use the connection method:

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

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

Schema::create('users', function ($table) {    $table->engine = 'InnoDB';    $table->increments('id');});
Rename/delete a table

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

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

To delete an existing data table, use the drop or dropIfExists method:

Create a column

To update an existing table, use the table method on the Schema facade. like the create method, the table method receives two parameters: table name and the closure of the Blueprint instance used to add columns to the table:

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

Of course, the table schema builder contains a series of column types that you can use to build a table:

Command Description
$ Table-> bigIncrements ('id '); Auto-increment ID, type: bigint
$ Table-> bigInteger ('votes '); Equivalent to the BIGINT type in the database
$ Table-> binary ('data '); Equivalent to the BLOB type in the database
$ Table-> boolean ('firmed '); Equivalent to the BOOLEAN type in the database
$ Table-> char ('name', 4 ); Equivalent to the CHAR type in the database
$ Table-> date ('created _ '); Equivalent to the DATE type in the database
$ Table-> dateTime ('created _ '); Equivalent to the DATETIME type in the database
$ Table-> decimal ('amount', 5, 2 ); It is equivalent to the DECIMAL type in the database and has a precision and range.
$ Table-> double ('column ', 15, 8 ); Equivalent to the DOUBLE type in the database, with precision, a total of 15 digits, 8 digits after the decimal point.
$ Table-> enum ('choices', ['foo', 'bar']); Equivalent to the ENUM type in the database
$ Table-> float ('amount '); Equivalent to the FLOAT type in the database
$ Table-> increments ('id '); Database primary key auto-increment ID
$ Table-> integer ('votes '); Equivalent to the INTEGER type in the database
$ Table-> json ('options '); Equivalent to the JSON type in the database
$ Table-> jsonb ('options '); Equivalent to the JSONB type in the database
$ Table-> longText ('Description '); Equivalent to the LONGTEXT type in the database
$ Table-> mediumInteger ('numbers '); Equivalent to the MEDIUMINT type in the database
$ Table-> mediumText ('Description '); Equivalent to the MEDIUMTEXT type in the database
$ Table-> morphs ('taggable '); Add an INTEGER-type taggable_id column and a STRING-type taggable_type column
$ Table-> nullableTimestamps (); The value is the same as timestamps (), but the NULL value is not allowed.
$ Table-> rememberToken (); Add a remember_token column: VARCHAR (100) NULL.
$ Table-> smallInteger ('votes '); Equivalent to the SMALLINT type in the database
$ Table-> softDeletes (); Add a deleted_at column for soft deletion.
$ Table-> string ('email '); It is equivalent to the VARCHAR column in the database.
$ Table-> string ('name', 100 ); Equivalent to VARCHAR in a database, with a length
$ Table-> text ('Description '); Equivalent to the TEXT type in the database
$ Table-> time ('Sunrise '); Equivalent to the TIME type in the database
$ Table-> tinyInteger ('numbers '); Equivalent to the TINYINT type in the database
$ Table-> timestamp ('added _ on '); Equivalent to the TIMESTAMP type in the database
$ Table-> timestamps (); Add the created_at and updated_at columns.
$ Table-> uuid ('id '); Equivalent to the UUID of the database
Column modifier

In addition to the column types listed above, you can also use some other column "modifiers" when adding columns. for example, to set the column to null by default, you can use the nullable method:

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

The following is a list of all available column modifiers that do not contain the index modifier:

Modifier Description
-> First () Set this column as the first column in the table (for MySQL only)
-> After ('column ') Place this column after another column (for MySQL only)
-> Nullable () The value of this column is allowed to be NULL.
-> Default ($ value) Default value of the specified column
-> Unsigned () Set integer columns to UNSIGNED
Prerequisites for modifying a column

Before modifying the column, make sure that the doctrine/dbal dependency has been added to composer. json file. The Doctrine DBAL library is used to determine the current state of a column and create an SQL query as required to adjust the column.

Update column attributes

The change method allows you to modify existing columns as new types or column attributes. For example, you may want to increase the size of a string column, so we can increase the size of the name column from 25 to 50:

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

We can also modify the allowed NULL value of this column:

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

To rename a column, you can use the renameColumn method on the table schema builder to ensure that the doctrine/dbal dependency has been added to the composer. json file before renaming a column:

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

Note: You cannot rename an enum column.

Delete column

To delete a column, use the dropColumn method on the table schema builder:

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

You can delete multiple columns from the table by passing an array of column names to the dropColumn method:

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

Note: Before deleting columns from the SQLite database, you must add doctrine/dbal dependencies to the composer. json file and run the composer update command on the terminal to install the library. In addition, the SQLite database does not support deleting or modifying multiple columns in a single migration.

Create an index

The table schema builder supports multiple types of indexes. First, let's look at an example where the specified column value is a unique index. To create an index, you can use the unique method:


In addition, you can create an index after defining a column, for example:


You can even pass the column name array to the index method to create a composite index:

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

Laravel automatically generates a reasonable index name, but you can pass the second parameter to this method to specify the index name:

$table->index('email', 'my_index_name');
Available index types
Command Description
$ Table-> primary ('id '); Add primary key index
$ Table-> primary (['first', 'last']); Add a hybrid index
$ Table-> unique ('email '); Add a unique index
$ Table-> unique ('state', 'My _ index_name '); Custom Index Name
$ Table-> index ('state '); Add common index
Delete index

To delete an index, you must specify the index name. By default, Laravel automatically assigns an appropriate name to the index-a simple connection table name, column name, and index type. The following are some examples:

Command Description
$ Table-> dropPrimary ('users _ id_primary '); Delete the primary key index from the "users" table
$ Table-> dropUnique ('users _ email_unique '); Delete a unique index from the "users" table
$ Table-> dropIndex ('geo _ state_index '); Delete a common index from the "geo" table
Foreign key constraint

Laravel also provides support for creating foreign key constraints to force reference integrity at the database level. For example, in the posts table, we define a user_id column that references the id column of the users table:

Schema::table('posts', function ($table) {    $table->integer('user_id')->unsigned();    $table->foreign('user_id')->references('id')->on('users');});

You can also specify the expected action for the "on delete" and "on update" attributes of the constraint:

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

To delete a foreign key, you can use the dropForeign method. The foreign key constraint and the index use the same naming rules-connect the table name and foreign key name and add the suffix "_ foreign:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.