周大胖子 发表于 2019-6-5 17:58:24

Laravel 数据库模型与

// laravel
// 配置数据库的位置在 : .env 文件中
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=数据库名 [无引号]
DB_USERNAME=数据库用户名 [无引号]
DB_PASSWORD=数据库密码[无引号]



Migrations [数据库迁移:数据表的每次变动(创建、修改、删除)都对应一个迁移文件]
文件所在位置: database/migrations/

[迁移操作都是基于 Schema 门面来完成WWW\tt\vendor\laravel\framework\src\Illuminate\Database\Schema\Builder]

命令记录 :

    php artisan make:migration create_users_table --create=users# 创建数据表迁移文件 users为表名称

    php artisan make:migration alter_admins_add_nickname --table=admins# 更新数据表迁移文件

    前提:

      需要先通过 Composer 安装 doctrine/dbal 扩展包composer require doctrine/dbal

    执行变更:

    php artisan migrate    执行迁移

    php artisan migrate --force强制执行迁移

    php artisan migrate:rollback回滚迁移 【默认会退到最后一步】

    php artisan migrate:rollback --step=5   回滚最后五条迁移

    php artisan migrate:reset       【回滚所有迁移】

    php artisan migrate:fresh       【删除所有表】

    参考文献: https://laravelacademy.org/post/9580.html#toc_9[迁移操作命令行 与 内置函数]

class AlterAdminsAddNickname extends Migration
{
    /**
   * Run the migrations.
   *
   * @return void
   */
    public function up()
    {
      Schema::table('admins', function (Blueprint $table) {

            // 有个小问题,所有添加索引的时候都报错 ->index() 反正是个原则 就是判断;
            

            // 添加一个phone 字段 长度20 允许为空的列备注是:用户电话
            $table->string('phone', 20)->after('name')->nullable()->comment('用户电话');

            // 修改 name 的字段是 50个长度 ->change()
            $table->string('name', 50)->change();

            // 更换字段名address 为 address
            $table->renameColumn('address', 'address');

            // 将email 设置为 唯一索引
            // $table->string('email')->unique();
            
            // 将 name 字段设置为普通索引
            // $table->string('name')->index();

            // 主键索引通过 increments 方法创建,该方法会创建一个自动增长的主键索引
            // $table->increments('id');

            // 创建索引的其余方式 ,这样做的一个好处是一次支持传入多个字段,从而构建混合索引
            // $table->primary('id');
            // $table->index('name');
            // $table->unique('email');
            // $table->index(['name', 'email']);
            

            // 移除索引
            // $table->dropIndex('name');
            // $table->dropUnique('email');
            // $table->dropPrimary('id');

            // 添加外键
            // $table->foreign('user_id')->references('id')->on('users');

      });
    }

    /**
   * Reverse the migrations.
   *
   * @return void
   */
    public function down()
    {
      Schema::table('admins', function (Blueprint $table) {
            // 删掉email字段
            $table->dropColumn('email');

      });
    }
}

一个奇怪的现象: 所有索引 在执行数据库迁移时,都报错。 不知为何---怀疑是数据库版本问题



页: [1]
查看完整版本: Laravel 数据库模型与