07
06月
2024
Laravel 数据库迁移
Laravel 的 Schema
facade 提供数据库相关的支持,用于在所有 Laravel 支持的数据库系统中创建和操作表。
- 首先使用 Artisan 命令创建迁移文件
//会根据时间命名,在database/migrations/时间_create_users_table.php文件 php artisan make:migration create_users_table
- xxx_create_users_table.php
class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
- 然后是运行迁移
//该命令会在对应的数据库创建上方的users表 php artisan migrate
- 如果发现数据表结构错误或者想要回滚*(但是回滚只能回滚创建的,不能回滚修改的字段)
//回滚上一次操作(这里要注意,不要运行多次) php artisan migrate:rollback //回滚最后五个迁移 php artisan migrate:rollback --step=5 //回滚所有 php artisan migrate:reset
- 你可以在结构生成器上使用以下命令定义表的选项
//指定存储引擎默认myisam $table->engine = 'InnoDB'; //指定表的默认字符编码 $table->charset = 'utf8';
- 经常用到的字段类型
//相当于bigIncrements $table->id(); //相当于 BIGINT $table->bigInteger('votes'); //相当于带有长度的 CHAR $table->char('name', 100); //相当于 INTEGER $table->integer('votes'); //相当于带长度的 VARCHAR $table->string('name', 100); //相当于 TEXT $table->text('description'); //相当于 TIMESTAMP $table->timestamp('added_on', 0); //相当于 TINYINT $table->tinyInteger('votes'); //会创建可以为null的·created_at· ·updated_at· $table->timestamps(); //或创建可以为null的 ·deleted_at· $table->softDeletes();
- 创建表例子
public function up() { Schema::create('store', function (Blueprint $table) { $table->id(); $table->string('name', 100)->nullable()->default('')->comment('店铺名称'); $table->string('brand_name', 100)->nullable()->default('')->comment('品牌名称'); $table->tinyInteger('status')->nullable()->default(1)->comment('状态:1待审核,2正常, 3禁用'); $table->string('logo', 500)->nullable()->comment('店铺logo'); $table->string('imgs', 1000)->nullable()->comment('店铺图片介绍'); $table->text('dec')->nullable()->comment('店铺简介'); $table->string('remark', 500)->nullable()->default('')->comment('备注'); $table->string('tags_name', 1000)->nullable()->comment('标签名称'); $table->text('cate_path_ids')->nullable()->comment('分类ID'); $table->timestamps(); $table->softDeletes(); $table->engine = 'InnoDB'; }); }
- 修改表例子
public function up() { Schema::table('news', function (Blueprint $table) { //在img字段后创建exhibit_id字段 $table->bigInteger('exhibit_id')->default(0)->after('img')->comment('关联展会ID'); //字段修改为 nullable $table->string('name', 50)->nullable()->change(); }); }
- 最后注意,
最好只用创建,不用修改,因为回滚不会回滚修改的;
非特殊说明,本文版权归 无限。 所有,转载请注明出处.
本文标题: 使用Laravel进行数据迁移
评论
沟通交流,拉近你我!