laravel migration

官方文档:https://laravel.com/docs/5.5/migrations

一,生成迁移

php artisan make:migration create_表名(复数)_table

例如新建一个admins表

php artisan make:migration create_admins_table

 

注意make:migration有1个必写的参数name, 3个可选的选项 –create,–tabel,–path

  1. –path是指定迁移文件生成的位置,默认是放在 应用根目录/database/migrations下面,如果指定了–path=x/y/x,就会在 应用根目录/x/y/z下面生成迁移文件,注意的是得保证该目录已存在,否则会报错
  2. 新建表时,name的写法可以是 create_表名_table,这种写法,后面的create可以省略,否则不能省,如make:migration wang –create=members
  3. 选项前有两个减号–,新手易写掉一个
  4. –create=表名,新建一个表,表名一般全为小写字母,复数形式
  5. –table=表名,修改现成的表
  6. –create与–tabel是2选1
  7. 在命令行自动生成的迁移文件只能是在当前项目下,如果想在项目外如vendor/包/模块中生成迁移文件,得手工编写,或自动生成后拷贝到指定地方,但要注意的是模块中的服务提供商中得写publish方法
  8. 生成的迁移文件名格式是 yyyy_mm_dd_His_name.php,文件中类名是将name写在大驼峰的格式,如name为create_admins_table变成class CreateAdminsTable extends Migration
  9. 生成的文件名是可以修改的,用来调整顺序,系统的排序是asort(名字名组成的数组,SORT_REGULAR ); 以升序的方式排列的,所以改名时要注意
  10. 没有运行migrate之前,迁移文件是可以手工删除和改名,修改内容的

二,编辑迁移

up是migrate时执行的方法 
down是migrate:rollback,migrate:reset,migrate:fresh,migrate:refresh时会执行的方法 
Facade(有人翻译成门面,我觉得翻译成表面比较合适些) Schema::方法实际上是执行 \Illuminate\Database\Schema\MySqlBuilder的方法,分下面几种

判断的有 hasTable,hasColumn,hasColumns 
读取的有 getAllTables,getColumnListing,getColumnType,getConnection 
设置的有 setConnection,blueprintResolver 
删除的有 dropAllTables 
操作的有 rename,enableForeignKeyConstraints,disableForeignKeyConstraints 
* 迁移常用有 create,table,drop,dropIfExists *

Blueprint(翻译成蓝图),其实就是代表一个数据库中的表,它的方法主要有2种,一是针对命令commands的方法,另是针对列columns的方法,命令和列都是一个流Fluent对象,处理命令的方法不多,主要熟悉的是处理列的方法,下面是针对Mysql数据的一些列方法和修饰器

 
class CreateArticleTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('article', function (Blueprint $table) {
            $table->increments('id')->comment('文章ID');
            $table->string('title',50)->unique()->comment('文章标题');
            $table->string('author')->comment('文章作者');
            $table->longText('content')->comment('文章内容');
            $table->timestamp('add_time')->comment('添加时间');
//            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('article');
    }
}

猜你喜欢

转载自www.cnblogs.com/xzj8023tp/p/9285016.html