transfer


1. Introduction

Migration is like database version control, which allows teams to easily edit and share the database table structure of applications. Migration is usually paired with Larave's structure builder to easily build the database table structure of applications.

Laravel's Schema Facade It provides database system independent support for creating and manipulating tables, and provides consistent, elegant, and smooth APIs in all database systems supported by Larave.

2. Generate Migration

use Artisan Command make:migration To create a new migration:

 php artisan make:migration create_users_table

The new migration is located in database/migrations Directory, each migration file name contains a timestamp to allow Larvel to determine its order.

--table and --create Option can be used to specify the table name and whether the migration needs to create a new data table. These options simply need to be placed after the above migration command and the table name needs to be specified:

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

If you want to specify a custom output path for generating migration, run the make:migration You can use the --path Option. The provided path should be relative to the application root directory.

3. Migration Structure

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

In these two methods, you need to use Laravel's table structure builder to create and modify tables. You want to learn Schema More useful methods of builder can View their documents For example, let's first look at creating flights A simple example of a table:

 <? php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateFlightsTable extends Migration{ /** *Run Migration * * @return void */ public function up() { Schema::create('flights', function (Blueprint $table) { $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 migrations in the application, you can use the migrate method. If you are using Homestead virtual machine , you should run the following command in your virtual machine:

 php artisan migrate

If you encounter an error prompt of "class not found" when running again, try running composer dump-autoload Command and rerun the migration command.

Force migration in production environment

Some migration operations are destructive, 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 force these commands to run without being prompted, use --force

 php artisan migrate --force

4.1 Rollback migration

To rollback the latest migration operation, you can use the rollback Command. Note that this will roll back the last run migration, which may contain multiple migration files:

 php artisan migrate:rollback

migrate:reset The command will rollback all application migrations:

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

migrate:refresh The command will rollback all database migrations first, and then run migrate Command. This command can effectively rebuild the entire database:

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

5. Write Migration

5.1 Creating tables

use Schema On the facade create Method to create a new data table. create Method receives two parameters, the first is the table name, and the second is to obtain the Blueprint Closure of object:

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

Of course, when creating a new table, you can use any of the Column method To define the columns of the data table.

5.1.1 Check whether the table/column exists

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

 if (Schema::hasTable('users')) { // } if (Schema::hasColumn('users', 'email')) { // }
5.1.2 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 connection method:

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

To set the storage engine of a table, set it on the table structure builder engine Properties:

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

5.2 Rename/Delete Table

To rename an existing data table, use rename method:

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

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

 Schema::drop('users'); Schema::dropIfExists('users');

5.3 Creating Columns

To update an existing table, use the table Methods, and create In the same way, table The method receives two parameters: the table name and the Blueprint Closure of instance:

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

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

command describe
$table->bigIncrements('id'); Self increasing ID, type bigint
$table->bigInteger('votes'); Equivalent to BIGINT type in database
$table->binary('data'); Equivalent to BLOB type in database
$table->boolean('confirmed'); Equivalent to BOOLEAN type in database
$table->char('name', 4); Equivalent to the CHAR type in the database
$table->date('created_at'); Equivalent to the DATE type in the database
$table->dateTime('created_at'); Equivalent to DATETIME type in database
$table->decimal('amount', 5, 2); Equivalent to DECIMAL type in database, with a precision and range
$table->double('column', 15, 8); It is equivalent to the DOUBLE type in the database, with precision, 15 digits in total, and 8 digits after the decimal point
$table->enum('choices', ['foo', 'bar']); Equivalent to ENUM type in database
$table->float('amount'); Equivalent to FLOAT type in database
$table->increments('id'); Database primary key auto increment ID
$table->integer('votes'); Equivalent to INTEGER type in database
$table->json('options'); Equivalent to JSON type in database
$table->jsonb('options'); Equivalent to JSONB type in database
$table->longText('description'); Equivalent to the LONGTEXT type in the database
$table->mediumInteger('numbers'); Equivalent to MEDIUMINT type in database
$table->mediumText('description'); Equivalent to MEDIUMTEXT type in database
$table->morphs('taggable'); Add an INTEGER type taggable_id Column and a STRING taggable_type column
$table->nullableTimestamps(); And timestamps() Same, but NULL value is not allowed
$table->rememberToken(); Add a remember_token Column: VARCHAR (100) NULL
$table->smallInteger('votes'); Equivalent to SMALLINT type in database
$table->softDeletes(); Add one deleted_at Column is used for soft deletion
$table->string('email'); Equivalent to the VARCHAR column in the database
$table->string('name', 100); Equivalent to VARCHAR in the database, with a length
$table->text('description'); Equivalent to TEXT type in database
$table->time('sunrise'); Equivalent to TIME type in database
$table->tinyInteger('numbers'); Equivalent to TINYINT type in database
$table->timestamp('added_on'); Equivalent to TIMESTAMP type in database
$table->timestamps(); Add created_at And updated_at Column
5.3.2 Column Modifiers

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

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

The following is a list of all available column modifiers, which does not contain Index Modifier

Modifier describe
->first() Set this column as the first column in the table (only applicable to MySQL)
->after('column') Place this column after another column (MySQL only)
->nullable() Allow the value of this column to be NULL
->default($value) Specify default values for columns
->unsigned() Settings integer Column is UNSIGNED

5.4 Modifying Columns

5.4.1 Prerequisites

Before modifying a column, make sure that the doctrine/dbal Dependencies added to composer.json File. The Doctrine DBAL library is used to determine the current state of the column and create SQL queries when necessary to make specified adjustments to the column.

5.4.2 Updating Column Attributes

change Method allows you to modify an existing column to a new type, or modify the properties of the column. For example, you may want to increase the size of the string type column, let's name Column size increased from 25 to 50:

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

We can also modify the column to allow NULL values:

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

To rename a column, use the renameColumn Method, before renaming a column, ensure that doctrine/dbal Dependencies have been added to composer.json File:

 Schema::table('users', function ($table) { $table->renameColumn('from', 'to'); });
Note: renaming of enum type columns is temporarily not supported.

5.5 Delete Column

To delete a column, use the dropColumn method:

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

You can pass the column name array to dropColumn Method to delete multiple columns from the table:

 Schema::table('users', function ($table) { $table->dropColumn(['votes', 'avatar', 'location']); });
Note: Before deleting columns from SQLite database, you need to add doctrine/dbal Depends on composer.json File and run in the terminal composer update Command to install the library.

5.6 Creating indexes

The table structure builder supports multiple types of indexes. First, let's look at an example of specifying column values as unique indexes. To create an index, you can use the unique method:

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

In addition, you can create indexes after defining columns, such as:

 $table->unique('email');

You can even create a hybrid index by passing the column name array to the index method:

 $table->index(['account_id', 'created_at']);
5.6.1 Available Index Types
command describe
$table->primary('id'); Add Primary Key Index
$table->primary(['first', 'last']); Add Mixed Index
$table->unique('email'); Add Unique Index
$table->index('state'); Add Normal Index

5.7 Deleting an index

To delete an index, you must specify an index name. By default, Larvel automatically assigns the appropriate name to the index -- simple join table name, column name, and index type. Here are some examples:

command describe
$table->dropPrimary('users_id_primary'); Delete the primary key index from the "users" table
$table->dropUnique('users_email_unique'); Remove the unique index from the "users" table
$table->dropIndex('geo_state_index'); Remove the normal index from the "geo" table

5.8 Foreign key constraints

Larave also provides support for creating foreign key constraints to enforce referential integrity at the database level. For example, we posts A reference is defined in the table users Of table id Column user_id Column:

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

You can also specify the desired action for the constraint's "on delete" and "on update" attributes:

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

To delete a foreign key, use the dropForeign method. Foreign key constraints and indexes use the same naming rule - join table names, foreign key names, and then add the suffix "_foreign":

 $table->dropForeign('posts_user_id_foreign');

give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: Query Builder

>>Next: Fill Data