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:
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
Add fields
\database\migrations \2017_07_30_133748_create_users_table.php
<?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('users',function (Blueprint $table){ $table->increments('id')->comment('递增ID'); $table->string('email',60)->comment('会员Email'); $table->string('phone',20)->comment('会员手机号'); $table->string('username',60)->comment('用户名'); $table->string('password',32)->comment('用户密码'); $table->char('rank',10)->comment('会员等级'); $table->unsignedSmallInteger('sex')->comment('性别;0保密;1男;2女'); $table->unsignedSmallInteger('status')->comment('用户状态'); $table->ipAddress('last_ip')->default('0.0.0.0')->comment('最后一次登录IP'); $table->timeTz('last_login')->comment('最后一次登录时间'); $table->timestamps(); }); } /** * 回滚数据库迁移 * * @return void */ public function down() { // Schema::drop('users'); } }
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:
if (Schema::hasTable('users')) { // } if (Schema::hasColumn('users', 'email')) { // }
If you want to perform database structure operations in a non-default database connection, you can use connection method:
Schema::connection('foo')->create('users', function (Blueprint $table) { $table->increments('id'); });
You can set the engine attribute on the database structure constructor to set the storage engine of the data table:
Schema::create('users', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); });
Renaming and deleting data tables
Schema::rename($from, $to);//重命名 //删除已存在的数据表 Schema::drop('users'); Schema::dropIfExists('users');
Creating fields
Schema::table('users', function (Blueprint $table) { $table->string('email'); });
命令 | 描述 |
---|---|
$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 型态。 |
字段修饰
Schema::table('users', function (Blueprint $table) { $table->string('email')->nullable(); });
Modifier | Description |
---|---|
->after('column') | 将此字段放置在其它字段「之后」(仅限 MySQL) |
->comment('my comment') | 增加注释 |
->default($value) | 为此字段指定「默认」值 |
->first() | 将此字段放置在数据表的「首位」(仅限 MySQL) |
->nullable() | 此字段允许写入 NULL 值 |
->storedAs($expression) | 创建一个存储的生成字段 (仅限 MySQL) |
->unsigned() | 设置 integer 字段为 UNSIGNED |
->virtualAs($expression) | 创建一个虚拟的生成字段 (仅限 MySQL) |
字段更新
Schema::table('users', function (Blueprint $table) { $table->string('phone',20)->change(); $table->string('username',60)->->nullable()->change(); });
重命名字段
Schema::table('users', function (Blueprint $table) { $table->renameColumn('from', 'to'); });
字段移除
Schema::table('users', function (Blueprint $table) { $table->dropColumn(['last_ip', 'last_login']); });
在使用字段更新,重命名字段,字段移除之前,请务必在你的 composer.json文件require键名中添加值。然后composer update进行更新或
composer require doctrine/dbal
创建索引
$table->string('email')->unique();
Command | Description |
---|---|
$table->primary('id'); | 加入主键。 |
$table->primary(['first', 'last']); | 加入复合键。 |
$table->unique('email'); | 加入唯一索引。 |
$table->unique('state', 'my_index_name'); | 自定义索引名称。 |
$table->unique(['first', 'last']); | 加入复合唯一键。 |
$table->index('state'); | 加入基本索引。 |
开启和关闭外键约束
Schema::enableForeignKeyConstraints(); Schema::disableForeignKeyConstraints();
运行迁移
php artisan migrate
在线上环境强制执行迁移
php artisan migrate --force
回滚迁移
若要回滚最后一次迁移,则可以使用 rollback 命令。此命令是对上一次执行的「批量」迁移回滚,其中可能包括多个迁移文件:
php artisan migrate:rollback
在 rollback 命令后加上 step 参数,你可以限制回滚迁移的个数。例如,下面的命令将会回滚最后的 5 个迁移。
php artisan migrate:rollback --step=5
migrate:reset 命令可以回滚应用程序中的所有迁移:
php artisan migrate:reset
使用单个命令来执行回滚或迁移
migrate:refresh 命令不仅会回滚数据库的所有迁移还会接着运行 migrate 命令。所以此命令可以有效的重新创建整个数据库:
php artisan migrate:refresh // 刷新数据库结构并执行数据填充 php artisan migrate:refresh --seed
使用 refresh 命令并加上 step 参数,你也可以限制执行回滚和再迁移的个数。比如,下面的命令会回滚并再迁移最后的 5 个迁移:
php artisan migrate:refresh --step=5
无法生成迁移文件
在 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 又可以执行上面的命令了。
相关推荐:
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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)