A detailed example of Laravel database migration method

Source: Internet
Author: User
This article mainly introduces the method of database migration of Laravel, small series think very good, now share to everyone, also give you a reference. Follow the small series together to see it, hope to help everyone.

Build migration

The--table and--create options can be used to specify the name of the data table or a new data table that will be created when the migration is executed. These options are required to fill in the specified data table when the migration file is pre-generated:


PHP artisan make:migration create_users_tablephp artisan make:migration create_users_table--create=usersphp Artisan Make:migration add_votes_to_users_table--table=users

Add Field

\database\migrations\2017_07_30_133748_create_users_table.php


<?phpuse Illuminate\support\facades\schema;use Illuminate\database\schema\blueprint;use Illuminate\Database\  Migrations\migration;class createuserstable extends migration{/** * Run database Migration * @return void */Public function Up () {//Schema::create (' Users ', function (Blueprint $table) {$table->increments (' id ')->comment (' incrementing        ID ');        $table->string (' email ',->comment) (' member email ');        $table->string (' phone ')->comment (' member mobile number ');        $table->string (' username ', $)->comment (' username ');        $table->string (' password ', +)->comment (' User password ');        $table->char (' Rank ',->comment (' Membership level ');        $table->unsignedsmallinteger (' Sex ')->comment (' gender; 0 confidentiality; 1 male; 2 female ');        $table->unsignedsmallinteger (' status ')->comment (' User status ');        $table->ipaddress (' last_ip ')->default (' 0.0.0.0 ')->comment (' Last login IP ');        $table->timetz (' Last_login ')->comment (' Last login time ');      $table->timestamps ();  }); }  /** * ROLLBACK DATABASE Migration * * @return void */Public function down () {//Schema::d rop (' users '); }}

To create a new data table, you can use the Create method of Schema facade. The Create method receives two parameters: the first parameter is the name of the data table, the second argument is a closure, and the closure receives a Blueprint object that defines the new data table

You can easily use the hastable and Hascolumn methods to check whether a data table or field exists:


if (schema::hastable (' users ')) {  //}if (' users ', ' email ') {  //}}

If you want to perform database structure operations in a non-default database connection, you can use the connection method:


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

You can set the engine properties on the database structure builder to set up the storage engines for the data tables:


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

Renaming and deleting data tables


Schema::rename ($from, $to);//rename/delete existing data table schema::d rop (' users '); Schema::d ropifexists (' users ');

Create a field


Schema::table (' Users ', function (Blueprint $table) {  $table->string (' email ');});
Command Description
$table->bigincrements (' id '); Increment ID (primary key), equivalent to "unsigned BIG integer" type.
$table->biginteger (' votes '); Equivalent to the BIGINT type State.
$table->binary (' data '); Equivalent to BLOB form.
$table->boolean (' confirmed '); Corresponds to a BOOLEAN pattern.
$table->char (' name ', 4); Equivalent to CHAR type, with length.
$table->date (' created_at '); Corresponds to the DATE type
$table->datetime (' created_at '); Corresponds to a DATETIME pattern.
$table->datetimetz (' created_at '); DATETIME (with time zone) pattern
$table->decimal (' Amount ', 5, 2); Equivalent to the DECIMAL type, with precision and cardinality.
$table->double (' column ', 15, 8); The equivalent of a DOUBLE type, with a total of 15 digits and 8 digits after the decimal point.
$table->enum (' Choices ', [' foo ', ' Bar ']); Equivalent to the ENUM type.
$table->float (' Amount ', 8, 2); The equivalent of a FLOAT pattern, with a total of 8 digits and 2 digits after the decimal point.
$table->increments (' id '); Incrementing the ID (primary key), using the equivalent of the "unsigned integer" form.
$table->integer (' votes '); Equivalent to an integer pattern.
$table->ipaddress (' visitor '); Equivalent to the IP address pattern.
$table->json (' options '); Equivalent to the JSON pattern.
$table->jsonb (' options '); Equivalent to the JSONB type State.
$table->longtext (' description '); Equivalent to the Longtext type State.
$table->macaddress (' device '); Corresponds to the MAC address pattern.
$table->mediumincrements (' id '); Increment ID (primary key), which is equivalent to "unsigned MEDIUM integer" form.
$table->mediuminteger (' numbers '); Equivalent to the Mediumint type State.
$table->mediumtext (' description '); Equivalent to the Mediumtext type State.
$table->morphs (' taggable '); Joins the integer taggable_id with the string taggable_type.
$table->nullablemorphs (' taggable '); Is the same as the morphs () field, but is allowed to be null.
$table->nullabletimestamps (); Same as timestamps (), but allowed to be NULL.
$table->remembertoken (); Add Remember_token and use VARCHAR (+) NULL.
$table->smallincrements (' id '); Increment ID (primary key), which is equivalent to "unsigned SMALL integer" form.
$table->smallinteger (' votes '); Equivalent to the SMALLINT type State.
$table->softdeletes (); Join the Deleted_at field for soft-delete operations.
$table->string (' email '); Equivalent to the VARCHAR pattern.
$table->string (' name ', 100); Equivalent to the VARCHAR type, with length.
$table->text (' description '); Corresponds to the TEXT type.
$table->time (' Sunrise '); Equivalent to the time pattern.
$table->timetz (' Sunrise '); Corresponds to time (with timezone) pattern.
$table->tinyinteger (' numbers '); Equivalent to the TINYINT type State.
$table->timestamp (' added_on '); Equivalent to the TIMESTAMP type State.
$table->timestamptz (' added_on '); Equivalent to TIMESTAMP (with time zone) pattern.
$table->timestamps (); Add the Created_at and Updated_at fields.
$table->timestampstz (); Joins the Created_at and Updated_at (with time zone) field and allows null.
$table->unsignedbiginteger (' votes '); Equivalent to Unsigned BIGINT type.
$table->unsignedinteger (' votes '); Equivalent to the Unsigned INT form.
$table->unsignedmediuminteger (' votes '); Equivalent to Unsigned mediumint type.
$table->unsignedsmallinteger (' votes '); Equivalent to Unsigned SMALLINT type.
$table->unsignedtinyinteger (' votes '); Equivalent to Unsigned TINYINT type.
$table->uuid (' id '); Equivalent to the UUID pattern.

Field Decoration


Schema::table (' Users ', function (Blueprint $table) {  $table->string (' email ')->nullable ();});
Modifier Description
->after (' column ') Place this field "after" in other fields (MySQL only)
->comment (' my comment ') Add Comment
->default ($value) Specify a "default" value for this field
->first () Place this field "first" in the datasheet (MySQL only)
->nullable () This field allows NULL values to be written
->storedas ($expression) Create a Stored build field (MySQL only)
->unsigned () Set integer field UNSIGNED
->virtualas ($expression) Create a Virtual build field (MySQL only)

Field Update


Schema::table (' Users ', function (Blueprint $table) {  $table->string (' phone ', ')->change ();  $table->string (' username ', $)->->nullable ()->change ();});

Rename Field


Schema::table (' Users ', function (Blueprint $table) {  $table->renamecolumn (' from ', ' to ');});

Field removal


Schema::table (' Users ', function (Blueprint $table) {  $table->dropcolumn ([' last_ip ', ' last_login ']);});

Before you use field updates, rename fields, and remove fields, be sure to add < "Doctrine/dbal": "^2.5" > values in your Composer.json file require key name. Then composer update for updates or


Composer require Doctrine/dbal

Create an index


$table->string (' email ')->unique ();
Command Description
$table->primary (' id '); Join the primary key.
$table->primary ([' First ', ' last ']); Add a composite key.
$table->unique (' email '); Join a unique index.
$table->unique (' state ', ' my_index_name '); The custom index name.
$table->unique ([' First ', ' last ']); Adds a composite unique key.
$table->index (' state '); Add a base index.

Turn foreign key constraints on and off


Schema::enableforeignkeyconstraints (); Schema::d isableforeignkeyconstraints ();

Run migration


PHP Artisan Migrate

Enforce migration on-line environment


PHP Artisan Migrate--force

Roll back migration

To roll back the last migration, you can use the rollback command. This command is a "bulk" migration rollback for the last execution, which may include multiple migration files:


PHP Artisan Migrate:rollback

You can limit the number of rollback migrations by adding the step parameter after the rollback command. For example, the following command will roll back the last 5 migrations.


PHP Artisan Migrate:rollback--step=5

The Migrate:reset command can roll back all migrations in the application:


PHP Artisan Migrate:reset

Use a single command to perform a rollback or migration

The Migrate:refresh command not only rolls back all migrations of the database but also runs the migrate command. Therefore, this command effectively re-creates the entire database:


PHP artisan migrate:refresh//Refresh the database structure and perform data filling PHP artisan Migrate:refresh--seed

You can also limit the number of rollback and re-migrations that are performed by using the Refresh command with the step parameter. For example, the following command rolls back and then migrates the last 5 migrations:


PHP Artisan Migrate:refresh--step=5

Unable to generate migration file

In the Laravel project, the database migration is sometimes created with PHP artisan make:migration create_xxx_table due to testing. If you delete the created migration file database/migrations/2017_07_30_133748_create_xxx_table.php file, execute PHP artisan make:migration again Create_ Xxx_table will error:

Copy the Code code as follows:


[Errorexception]
Include (e:\laraver\vendor\composer/. /.. /database/migrations/2017_07_30_133748_create_users_table.php): Failed to open stream:no such file or directory

Rerun composer Update to execute the above command.

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.