php artisan make:migration
https://learnku.com/docs/laravel/8.x/migrations/9403
创建新建表的迁移和修改表的迁移
php artisan make:migration create_orders_table --create=orders //创建订单表orders
php artisan make:migration add_tags_to_orders_table --table=orders//给orders表增加tags字段
执行迁移
php artisan migrate
一、常用的命令:
php artisan list 查看php artisan所有命令
php artisan --help 查看php artisan的用法
php artisan help admin:make 查看php artisan admin:make的用法
php artisan admin:make --help 查看php artisan admin:make的用法
php artisan make:migration create_users_table |
意思:创建一个迁移,其实就是创建一张名为users的表。
接着你便能在database/migrations这个目录下找到与2014_10_12_000000_create_users_table.php这个类似的文件。
和以前用php语句创建表一样,我们可以在2014_10_12_000000_create_users_table.php这个文件中写上我们要创建表的字段及约束条件。
–table和–create选项可以用于指定表名以及该迁移是否要创建一个新的数据表。这些选项只需要简单放在上述迁移命令后面并指定表名,如果你想要指定生成迁移的自定义输出路径,在执行make:migration命令时可以使用–path选项,提供的路径应该是相对于应用根目录的。
迁移结构
一个migration类包含两个方法up和down。
up中主要包含创建表的具体内容。
down中和前者相反。
Schema::create接受两个参数。第一个是你要创建表的表名;第二个是一个闭包(匿名函数),获取用于定义新表的 Blueprint 对象。
Migration
|
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
|
<?php use Illuminate\Support\Facades\Schema;use Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration{ /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); }} |
运行迁移
要运行应用中所有未执行的迁移,可以使用 Artisan 命令的migrate方法。
Migration
|
1
|
php artisan migrate |
回滚迁移
想要回滚最新的一次迁移”操作“,可以使用rollback命令,注意这将会回滚最后一批运行的迁移,可能包含多个迁移文件:
Migration
|
1
|
php artisan migrate:rollback |
migrate:reset命令将会回滚所有的应用迁移:
Migration
|
1
|
php artisan migrate:reset |
在单个命令中回滚/迁移
migrate:refresh命令将会先回滚所有数据库迁移,然后运行migrate命令。这个命令可以有效的重建整个数据库:
Migration
|
1
2
|
php artisan migrate:refreshphp artisan migrate:refresh --seed |
常用迁移属性
| $table->increments(‘id'); | 数据库主键自增 ID |
| $table->integer(‘votes'); | 等同于数据库中的 INTEGER 类型 |
| $table->float(‘amount'); | 等同于数据库中的 FLOAT 类型 |
| $table->char(‘name', 4); | 等同于数据库中的 CHAR 类型 |
| $table->dateTime(‘created_at'); | 等同于数据库中的 DATETIME 类型 |
| $table->enum(‘choices', [‘foo','bar']); | 等同于数据库中的 ENUM 类型 |
| $table->tinyInteger(‘numbers'); | 等同于数据库中的 TINYINT 类型 |
| $table->timestamps(); | 添加 created_at 和 updated_at 列 |
一些列名约束条件的写法
Migration
|
1
2
3
|
Schema::table('users', function ($table) { $table->integer('votes')->unsigned(); //无符号类型}); |
常用约束
| ->first() | 将该列置为表中第一个列 (仅适用于 MySQL) |
| ->after(‘column') | 将该列置于另一个列之后 (仅适用于 MySQL) |
| ->nullable() | 允许该列的值为 NULL |
| ->default($value) | 指定列的默认值 |
| ->unsigned() | 设置 integer 列为 UNSIGNED |

浙公网安备 33010602011771号