Home Backend Development PHP Tutorial Detailed example of Laravel database migration method

Detailed example of Laravel database migration method

Jan 30, 2018 pm 02:24 PM
laravel database migrate

This article mainly introduces Laravel's database migration method. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Generate 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 need to be filled in the specified data table when pre-generating the migration file:


1

2

3

php artisan make:migration create_users_table

php artisan make:migration create_users_table --create=users

php artisan make:migration add_votes_to_users_table --table=users

Copy after login

Add fields

\database\migrations \2017_07_30_133748_create_users_table.php


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

<?php

 

use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;

 

class CreateUsersTable extends Migration

{

  /**

   * 运行数据库迁移

   *

   * @return void

   */

  public function up()

  {

    //

      Schema::create(&#39;users&#39;,function (Blueprint $table){

        $table->increments(&#39;id&#39;)->comment(&#39;递增ID&#39;);

        $table->string(&#39;email&#39;,60)->comment(&#39;会员Email&#39;);

        $table->string(&#39;phone&#39;,20)->comment(&#39;会员手机号&#39;);

        $table->string(&#39;username&#39;,60)->comment(&#39;用户名&#39;);

        $table->string(&#39;password&#39;,32)->comment(&#39;用户密码&#39;);

        $table->char(&#39;rank&#39;,10)->comment(&#39;会员等级&#39;);

        $table->unsignedSmallInteger(&#39;sex&#39;)->comment(&#39;性别;0保密;1男;2女&#39;);

        $table->unsignedSmallInteger(&#39;status&#39;)->comment(&#39;用户状态&#39;);

        $table->ipAddress(&#39;last_ip&#39;)->default(&#39;0.0.0.0&#39;)->comment(&#39;最后一次登录IP&#39;);

        $table->timeTz(&#39;last_login&#39;)->comment(&#39;最后一次登录时间&#39;);

        $table->timestamps();

      });

  }

 

  /**

   * 回滚数据库迁移

   *

   * @return void

   */

  public function down()

  {

    //

    Schema::drop(&#39;users&#39;);

  }

}

Copy after login

To create a new data table, you can use the create method of the Schema facade. The create method receives two parameters: the first parameter is the name of the data table, and the second parameter is a closure. This closure will receive a Blueprint object used to define a new data table.

You can conveniently Use the hasTable and hasColumn methods to check whether the data table or field exists:


1

2

3

4

5

6

if (Schema::hasTable(&#39;users&#39;)) {

  //

}

if (Schema::hasColumn(&#39;users&#39;, &#39;email&#39;)) {

  //

}

Copy after login

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


1

2

3

Schema::connection(&#39;foo&#39;)->create(&#39;users&#39;, function (Blueprint $table) {

  $table->increments(&#39;id&#39;);

});

Copy after login

You can set the engine attribute on the database structure constructor to set the storage engine of the data table:


1

2

3

4

Schema::create(&#39;users&#39;, function (Blueprint $table) {

  $table->engine = &#39;InnoDB&#39;;

  $table->increments(&#39;id&#39;);

});

Copy after login

Renaming and deleting data tables


1

2

3

4

5

Schema::rename($from, $to);//重命名

 

//删除已存在的数据表

Schema::drop(&#39;users&#39;);

Schema::dropIfExists(&#39;users&#39;);

Copy after login

Creating fields


1

2

3

Schema::table(&#39;users&#39;, function (Blueprint $table) {

  $table->string(&#39;email&#39;);

});

Copy after login
命令描述
$table->bigIncrements('id');递增 ID(主键),相当于「UNSIGNED BIG INTEGER」型态。
$table->bigInteger('votes');相当于 BIGINT 型态。
$table->binary('data');相当于 BLOB 型态。
$table->boolean('confirmed');相当于 BOOLEAN 型态。
$table->char('name', 4);相当于 CHAR 型态,并带有长度。
$table->date('created_at');相当于 DATE 型态
$table->dateTime('created_at');相当于 DATETIME 型态。
$table->dateTimeTz('created_at');DATETIME (带时区) 形态
$table->decimal('amount', 5, 2);相当于 DECIMAL 型态,并带有精度与基数。
$table->double('column', 15, 8);相当于 DOUBLE 型态,总共有 15 位数,在小数点后面有 8 位数。
$table->enum('choices', ['foo', 'bar']);相当于 ENUM 型态。
$table->float('amount', 8, 2);相当于 FLOAT 型态,总共有 8 位数,在小数点后面有 2 位数。
$table->increments('id');递增的 ID (主键),使用相当于「UNSIGNED INTEGER」的型态。
$table->integer('votes');相当于 INTEGER 型态。
$table->ipAddress('visitor');相当于 IP 地址形态。
$table->json('options');相当于 JSON 型态。
$table->jsonb('options');相当于 JSONB 型态。
$table->longText('description');相当于 LONGTEXT 型态。
$table->macAddress('device');相当于 MAC 地址形态。
$table->mediumIncrements('id');递增 ID (主键) ,相当于「UNSIGNED MEDIUM INTEGER」型态。
$table->mediumInteger('numbers');相当于 MEDIUMINT 型态。
$table->mediumText('description');相当于 MEDIUMTEXT 型态。
$table->morphs('taggable');加入整数 taggable_id 与字符串 taggable_type。
$table->nullableMorphs('taggable');与 morphs() 字段相同,但允许为NULL。
$table->nullableTimestamps();与 timestamps() 相同,但允许为 NULL。
$table->rememberToken();加入 remember_token 并使用 VARCHAR(100) NULL。
$table->smallIncrements('id');递增 ID (主键) ,相当于「UNSIGNED SMALL INTEGER」型态。
$table->smallInteger('votes');相当于 SMALLINT 型态。
$table->softDeletes();加入 deleted_at 字段用于软删除操作。
$table->string('email');相当于 VARCHAR 型态。
$table->string('name', 100);相当于 VARCHAR 型态,并带有长度。
$table->text('description');相当于 TEXT 型态。
$table->time('sunrise');相当于 TIME 型态。
$table->timeTz('sunrise');相当于 TIME (带时区) 形态。
$table->tinyInteger('numbers');相当于 TINYINT 型态。
$table->timestamp('added_on');相当于 TIMESTAMP 型态。
$table->timestampTz('added_on');相当于 TIMESTAMP (带时区) 形态。
$table->timestamps();加入 created_at 和 updated_at 字段。
$table->timestampsTz();加入 created_at and updated_at (带时区) 字段,并允许为NULL。
$table->unsignedBigInteger('votes');相当于 Unsigned BIGINT 型态。
$table->unsignedInteger('votes');相当于 Unsigned INT 型态。
$table->unsignedMediumInteger('votes');相当于 Unsigned MEDIUMINT 型态。
$table->unsignedSmallInteger('votes');相当于 Unsigned SMALLINT 型态。
$table->unsignedTinyInteger('votes');相当于 Unsigned TINYINT 型态。
$table->uuid('id');相当于 UUID 型态。

字段修饰


1

2

3

Schema::table(&#39;users&#39;, function (Blueprint $table) {

  $table->string(&#39;email&#39;)->nullable();

});

Copy after login
ModifierDescription
->after('column')将此字段放置在其它字段「之后」(仅限 MySQL)
->comment('my comment')增加注释
->default($value)为此字段指定「默认」值
->first()将此字段放置在数据表的「首位」(仅限 MySQL)
->nullable()此字段允许写入 NULL 值
->storedAs($expression)创建一个存储的生成字段 (仅限 MySQL)
->unsigned()设置 integer 字段为 UNSIGNED
->virtualAs($expression)创建一个虚拟的生成字段 (仅限 MySQL)

字段更新


1

2

3

4

Schema::table(&#39;users&#39;, function (Blueprint $table) {

  $table->string(&#39;phone&#39;,20)->change();

  $table->string(&#39;username&#39;,60)->->nullable()->change();

});

Copy after login

重命名字段


1

2

3

Schema::table(&#39;users&#39;, function (Blueprint $table) {

  $table->renameColumn(&#39;from&#39;, &#39;to&#39;);

});

Copy after login

字段移除


1

2

3

Schema::table(&#39;users&#39;, function (Blueprint $table) {

  $table->dropColumn([&#39;last_ip&#39;, &#39;last_login&#39;]);

});

Copy after login

在使用字段更新,重命名字段,字段移除之前,请务必在你的 composer.json文件require键名中添加< "doctrine/dbal": "^2.5">值。然后composer update进行更新或


1

composer require doctrine/dbal

Copy after login

创建索引


1

$table->string(&#39;email&#39;)->unique();

Copy after login
CommandDescription
$table->primary('id');加入主键。
$table->primary(['first', 'last']);加入复合键。
$table->unique('email');加入唯一索引。
$table->unique('state', 'my_index_name');自定义索引名称。
$table->unique(['first', 'last']);加入复合唯一键。
$table->index('state');加入基本索引。

开启和关闭外键约束


1

2

Schema::enableForeignKeyConstraints();

Schema::disableForeignKeyConstraints();

Copy after login

运行迁移


1

php artisan migrate

Copy after login

在线上环境强制执行迁移


1

php artisan migrate --force

Copy after login

回滚迁移

若要回滚最后一次迁移,则可以使用 rollback 命令。此命令是对上一次执行的「批量」迁移回滚,其中可能包括多个迁移文件:


1

php artisan migrate:rollback

Copy after login

在 rollback 命令后加上 step 参数,你可以限制回滚迁移的个数。例如,下面的命令将会回滚最后的 5 个迁移。


1

php artisan migrate:rollback --step=5

Copy after login

migrate:reset 命令可以回滚应用程序中的所有迁移:


1

php artisan migrate:reset

Copy after login

使用单个命令来执行回滚或迁移

migrate:refresh 命令不仅会回滚数据库的所有迁移还会接着运行 migrate 命令。所以此命令可以有效的重新创建整个数据库:


1

2

3

php artisan migrate:refresh

// 刷新数据库结构并执行数据填充

php artisan migrate:refresh --seed

Copy after login

使用 refresh 命令并加上 step 参数,你也可以限制执行回滚和再迁移的个数。比如,下面的命令会回滚并再迁移最后的 5 个迁移:


1

php artisan migrate:refresh --step=5

Copy after login

无法生成迁移文件

在 Laravel 项目中,由于测试,有时候用 PHP artisan make:migration create_xxx_table 创建数据库迁移。如果把创建的迁移文件 database/migrations/2017_07_30_133748_create_xxx_table.php 文件给删除了,再次执行 php artisan make:migration create_xxx_table 会报错:

复制代码 代码如下:


[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 

重新运行 composer update 又可以执行上面的命令了。

相关推荐:

PHP开发框架Laravel数据库操作方法总结

The above is the detailed content of Detailed example of Laravel database migration method. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Laravel's geospatial: Optimization of interactive maps and large amounts of data Laravel's geospatial: Optimization of interactive maps and large amounts of data Apr 08, 2025 pm 12:24 PM

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

How to effectively check the validity of Redis connections in Laravel6 project? How to effectively check the validity of Redis connections in Laravel6 project? Apr 01, 2025 pm 02:00 PM

How to check the validity of Redis connections in Laravel6 projects is a common problem, especially when projects rely on Redis for business processing. The following is...

Laravel and the Backend: Powering Web Application Logic Laravel and the Backend: Powering Web Application Logic Apr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

See all articles