Laravel迁移(Migration)

建表常用代码

主要是包括了设计表的过程中可能涉及的字段类型:

Schema::create('表名', function (Blueprint $table) {
    $table->increments('id');

    //定义字段又加索引
    $table->integer('category_id')->index()->notNull()->default(0)->comment('分类ID');
    $table->mediumInteger('forward_nums')->comment('转发数');

    //其实默认就是 notNull 的,后面的都不需要声明了
    $table->string('title', 255)->notNull()->default('')->comment('标题'); 

    //指定编码集
    $table->text('content')->charset('utf8mb4')->collation('utf8mb4_unicode_ci')->comment('内容');
    //反而需要允许为 null 的时候请明确声明 nullable
    $table->dateTime('last_cached_time')->nullable()->comment('最后缓存时间'); 
    $table->tinyInteger('source')->comment('来源:1=自由撰写,2=模板编辑,3=AI,4=转载');

    $table->timestamps(); //如果需要 created_at 和 updated_at 字段
    $table->softDeletes(); //如果模型有启用软删除
});

//migration 不自带设置表注释的支持,需要额外执行一条语句来设置表注释
DB::statement('ALTER TABLE `' . '表名,换成你的变量' . "` comment '表注释内容'");

复制以上代码后去掉你不需要的,把其它需要的复制一行改改名字即可建表。

后续疑问:指定表的编码集呢? 暂时还没有空找资料或看源码,欢迎留言


修改表结构

Schema::table('表名', function (Blueprint $table) {
    //添加字段,并指定在某个字段后面
    $table->integer('category_id')->index()->notNull()->default(0)->comment('分类ID')->after('title');

    //修改 source 字段的类型为 integer,并修改注释为“xxx”,注意后面 change
    $table->integer('source')->comment('xxx')->change();

    //删除字段
    $table->dropColumn('last_cached_time');

    //加普通索引
    $table->index('title');

    //给两个字段建联合索引
    $table->index(['category_id', 'title'])

    //加唯一索引
    $table->unique('title');

    //删除索引
    $table->dropIndex('title')
});

如果数据库有多个连接

这时候建表前就不能直接Schema::table()了,而是先要设置连接名称如Schema::connection(xxx)->table()

实例代码:

use App\Models\User;
//...

$model = new User();
$connection = Schema::connection($model->getConnection()->getName());
$connection->create($model->getTable(), function (Blueprint $table) {
    $table->increments('id');
    $table->integer('softuser_id')->comment('用户ID');
    $table->integer('total_result_money')->nullable()->comment('结果金额');
    $table->tinyInteger('residue_degree')->comment('剩余次数');
    $table->string('prize')->nullable()->comment('奖品描述');
    $table->dateTime('prize_expired_at')->nullable()->comment('奖品过期时间');
    $table->text('extra')->nullable()->comment('扩展信息');
    $table->timestamps();
});

//设置有注释的时候要另外 getConnection 才能得到一个可以执行 statement 的对象
$connection->getConnection()->statement('ALTER TABLE `' . $model->getTable() . "` COMMENT '用户'");
发布了57 篇原创文章 · 获赞 0 · 访问量 2177

猜你喜欢

转载自blog.csdn.net/zhidc/article/details/105315508
今日推荐