Common codes for building tables
Mainly includes the types of fields that may be involved in the design table process:
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 '表注释内容'");
After copying the above code, remove the ones you don't need, and copy the other required lines to change the name to build the table.
Follow-up questions: What about the encoding set of the specified table? There is no time to find information or see the source code, please leave a message
Modify the table structure
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')
});
If the database has multiple connections
At this time, you cannot directly Schema::table()
set up the table , but first set the connection name such asSchema::connection(xxx)->table()
Example code:
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 '用户'");