zoukankan      html  css  js  c++  java
  • Laravel 5.2 教程

    一、简介

    迁移(Migrations)是一种数据库的版本控制。可以让团队在修改数据库结构的同时,保持彼此的进度一致。迁移通常会和 结构生成器 一起使用,可以简单的管理数据库结构。

    下面以创建学生表的迁移为例,来介绍Laravel中迁移的使用。(点击查看演示数据表结构

    二、建立迁移文件

    1. 使用Artisan的 make:migration 命令生成students表的迁移文件

    1)生成一个最基本的迁移文件:

    php artisan make:migration create_students_table

    迁移文件在database/migrations目录下,打开该目录你将会看见以当前年月日开头名为create_students_table的php文件。

    2)如果生成的迁移文件中想带有表名,可以加上–table参数:

    php artisan make:migration create_students_table --table=students

    3)如果生成的迁移文件中想带有表名及基本的表字段,可以加上–create参数:

    php artisan make:migration create_students_table --create=students    

    4)生成模型的同时,如果想生成对应的迁移文件,只需要加上-m参数即可,迁移文件中的表名默认是模型的复数形式,如果不符合自己的需要,手动更改表名即可:

    php artisan make:model Student -m

    该条命令将会生成 Studnet.php 模型以及2016_07_30_052127_create_students_table.php 迁移文件。

    2. 结构生成器 (Schema)

    打开该文件后,有一个CreateStudentsTable的类,里面有up()和down()两个方法,up方法用于生成数据表,down方法用于删除数据表。按照数据表结构,完善后该类代码如下:

    <?php
    
    use IlluminateDatabaseSchemaBlueprint;
    use IlluminateDatabaseMigrationsMigration;
    
    class CreateStudentsTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('students', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->integer('age')->unsigned();
                $table->integer('sex')->unsigned()->default(10);
                $table->integer('created_at');
                $table->integer('updated_at');
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::drop('students');
        }
    }
    

    三、执行迁移

    在控制台执行以下命令,即可执行迁移文件,生成或更新相应的表。

    php artisan migrate

    四、回滚迁移

    1. 回滚上一次的迁移

    php artisan migrate:rollback

    2. 回滚所有迁移

    php artisan migrate:reset

    3. 回滚所有迁移并且再执行一次

    php artisan migrate:refresh
    php artisan migrate:refresh --seed

    交友互动:

    本文首发于马燕龙个人博客,欢迎分享,转载请标明出处。
    马燕龙个人博客:http://www.mayanlong.com
    马燕龙个人微博:http://weibo.com/imayanlong
    马燕龙Github主页:https://github.com/yanlongma

  • 相关阅读:
    我的插件架构
    .net 处理图片亮度
    封装自己的对称加密模块
    漏洞无处不在之窃取你的QQ信息
    写自己的自动升级模块
    抓到一只网马,发文顺便鄙视下360
    .net 3.5的Socket异步完成端口
    检测本机是否登录了指定QQ账号
    C++/CLR写的Data Blocks
    修改的Vista风格多功能日历Demo
  • 原文地址:https://www.cnblogs.com/imayanlong/p/6033024.html
Copyright © 2011-2022 走看看