Laravel Migrations

来源:转载

0 目的

创建Migrations主要的功能是为了让团队能保住使用的数据库结构一致

1 开玩

相关的命令( php artisan list)

migrate:install Create the migration repository migrate:refresh Reset and re-run all migrations migrate:reset Rollback all database migrations migrate:rollback Rollback the last database migration migrate:status Show the status of each migration

创建数据库表(手动创建表不会作用.),因为输入命令后,会在verdor/composer/autoload_classmap.php里映射类.如下

'Create_Disease_Type' => $baseDir . '/database/migrations/2015_11_02_153746_Create_Disease_Type.php', 'CreateInstitutes' => $baseDir . '/database/migrations/2015_11_02_143144_Create_Institutes.php', php artisan make:migration Create_Users --create=Users

创建基础类,设置id、时间戳和软删除.

一开始自己创建了个 Base_Table,不过那样也会创建一个表,所以直接把方法写在 Migration里

/** * 增加基本属性 * @param Blueprint $table */ public function add_base_attribute(Blueprint $table) { $table->increments('id'); //创建created_at和updated_at $table->timestamps(); //创建deleted_at $table->softDeletes(); return $table; }

创建外键,注意要先定义外键属性,再设定关系.

public function up() { Schema::create('Institutes', function (Blueprint $table) { $table->unsignedInteger('institute_ID'); $table->foreign('institute_ID') ->references('id')->on('institutes') ->onDelete('cascade'); $table = parent::add_base_attribute($table); }); } 错误处理 有依赖关系的表,要把外键的表先创建.

外键的属性类型要一致,否则会报错 General error: 1215 Cannot add foreign key constraint

//主表 $table->increments('id'); //从表 $table->unsignedInteger('institute_ID'); $table->foreign('institute_ID') ->references('id')->on('institutes') ->onDelete('cascade');

migrations类名不过有下划线

报错

PHP Fatal error: Class 'CreateInstitutes' not found in /Users/maizhikun/Learning/apache_sites/HapLab_Laravel/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php on line 324 [Symfony/Component/Debug/Exception/FatalErrorException] Class 'CreateInstitutes' not found //看了下报错地方的源代码.估计是下划线导致. public function resolve($file) { $file = implode('_', array_slice(explode('_', $file), 4)); $class = Str::studly($file); return new $class; }

后来又发现了错误.最后确定了是文件名(假如有下划线)会去掉下划线(从时间之后的下划线)然后找相对应的类名.



分享给朋友:
您可能感兴趣的文章:
随机阅读:
栏目列表
推荐内容