【问题标题】:How to use Migration in Laravel?如何在 Laravel 中使用迁移?
【发布时间】:2016-05-30 03:04:58
【问题描述】:

我目前是beginner of laravel。我正在从official docs 学习laravel 5.2。在 laravel 中研究了migration 之后,我非常清楚它的迁移概念。但是在通过脚本代码练习时,我遇到了一个问题。问题是,正如 laravel 告诉 laravel allows a team to easily modify and share the application's database schema 的那样。但是通过表的迁移文件创建后如何change the structure of database table。我找到了解决方案here。但我对8th step of the solution 表示怀疑,如果我运行该命令,那么将执行所有迁移填充。所以这会给我Table is already exists的错误。我对么?如果是,请用该链接中的示例进行解释。我想我只需要运行最后一个迁移文件2013_05_23_202930_update_users.php。如果这是答案,那么还键入命令来运行特定的单个迁移文件。如果有人知道答案,将不胜感激。

【问题讨论】:

    标签: laravel laravel-5.2 laravel-migrations


    【解决方案1】:

    创建表:

    if (!Schema::hasTable('users')) {
            Schema::create('users', function (Blueprint $table) {
                $table->engine = 'InnoDB';
                $table->increments('id')->unsigned();
                $table->string('username'); 
                $table->string('password', 60);                
                $table->timestamps();
                $table->softDeletes();
            });
        }
    

    要向该表添加一些列:

    php artisan make:migration add_somthing_to_users_table --table=users

    Schema::table('users', function (Blueprint $table) {
            //
            if (!Schema::hasColumn('users', 'fb_id')) {
                //
                $table->string('fb_id')->default('');
            }
        });
    

    【讨论】:

    • 那么你是说当我必须更新表时,我应该在 create_users 迁移文件中编写代码,然后运行与该链接第 8 步中提到的相同的命令?由于表已经创建,所以创建表的脚本将被跳过?还有,如果还有其他方法,比如单独的迁移文件,那么也请解释一下。
    • bdw 我对你的回答很满意。但是 laravel 以时间前缀命名迁移文件,所以我认为 laravel 建议为此类任务创建单独的文件。所以我告诉你替代解决方案。
    【解决方案2】:

    好的,伙计们,我找到了解决方案。在参考this link 之后,我知道发布的问题链接中的解决方案是正确的。由于某些我不知道的原因,桌子没有改变。但是重新启动我的系统后,它可以工作。但是@rome 的回答也是可以接受的。

    【讨论】:

      猜你喜欢
      • 2014-05-25
      • 2016-03-11
      • 2018-03-09
      • 2017-05-03
      • 2015-01-14
      • 1970-01-01
      • 2018-11-10
      • 2017-05-12
      相关资源
      最近更新 更多