数据表迁移
通过命令行在项目目录输入php artisan make:migration create_client_table 命令创建迁移文件,这里我准备创建client表,create_client_table是我的文件名字
php artisan make:migration create_client_table
于是在database/migrations/里面就生成一个文件
该命令后面还支持2个可选项,–create=name --table=name
‘=’ 等于号后面写你的表名,create是创建新表, --table是修改表
如果不写可选项的话,它会自动默认是–create
php artisan make:migration create_client_table --create=client
看一下生成的文件里面,up() 方法里面写你新增表的字段,这里生成的同时已经给你写了个新增主键big int(‘id’)的例子了
public function up()
{
Schema::create('client', function (Blueprint $table) {
$table->Increments('client_id',10);
$table->string('name',100)->comment('用户名');
$table->string('email',100)->unique()->comment('邮箱');
$table->string('password',16)->comment('密码');
$table->string('phone',11)->comment('电话号码');
$table->bigInteger('user_id',false)->unsigned()->comment('外键');
$table->tinyInteger('sex',false)->comment('性别');
$table->timestamps();
});
}
$table->Increments(‘client_id’,10);
创建一个自动增长的主键索引
$table->string(‘email’,100)->unique()->comment(‘邮箱’);
就是设置email为字符串,字段长度为100,唯一索引,注解为邮箱
接着运行数据库迁移命令:
$ php artisan migrate
Migrating: 2020_01_04_120630_create_client_table
Migrated: 2020_01_04_120630_create_client_table (0.1 seconds)
在刷新一下数据库,就能查看到刚才添加的数据表client表了
接下来试一下修改表:
$ php artisan make:migration modify_client --table=client
Created Migration: 2020_01_04_123919_modify_client
#如果你想修改表字段的话,需要composer安装doctrine/dbal扩展包
composer require doctrine/dbal
然后编写新生成的文件的up方法
public function up()
{
Schema::table('client', function (Blueprint $table) {
$table->string('nickname',255)->after('name')->nullable()->comment('昵称');
$table->renameColumn('phone','telphone');
#如果你是要修改字段的属性,后面要加个chage方法即可让变动生效
$table->string('name',50)->change();
});
}
再次运行数据库迁移命令
$ php artisan migrate
Migrating: 2020_01_04_123919_modify_client
Migrated: 2020_01_04_123919_modify_client (0.29 seconds)
再次查看数据库
修改成功
接下来试试索引和外键
$ php artisan make:migration modify_client_index_foreign --table=client
public function up()
{
Schema::table('client', function (Blueprint $table) {
$table->unique('phone');
$table->index(['name','password']);
$table->foreign('user_id','user_id_delete')->references('id')->on('users')->onDelete('cascade');
$table->foreign('user_id','user_id_update')->references('id')->on('users')->onUpdate('cascade');
});
}
$table->index([‘name’,‘password’]);
这个可以添加多个字段组合的混合索引,
$ php artisan migrate