添加具有外键的列

时间:2017-01-30 19:15:56

标签: php laravel laravel-5 laravel-5.3

我现有的表格如下

Story
-------------------------------
| id | name | author_id | date |

现在我想再添加一个外键列created_by如何在不删除现有数据的情况下添加它。现有数据外键必须是管理员ID。

从这个问题我了解了如何在不删除所有现有数据的情况下添加列。

How to add column in a table using laravel 5 migration without losing its data?

我想在我的电脑,测试机,直播服务器上进行此修改。所以我必须添加外键,我还必须从users表中找出admin id并分配给它。怎么做?

2 个答案:

答案 0 :(得分:1)

要添加列,您可以在--table artisan命令上引用带有make:migration标记的现有表:

php artisan make:migration add_created_by_column_to_story_table --table=story

然后在您的迁移中,它将使用table()方法而不是create()方法:

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('story', function(Blueprint $table) {
        $table->integer('created_by');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('story', function(Blueprint $table) {
        $table->dropColumn('created_by');
    });
}

答案 1 :(得分:0)

使用@Eric Tucker答案来创建迁移

现在使用created_by的新值更新数据库。我正在写你如何升级我的代码,它处理不同的服务器(在我的情况下本地,测试和生产)。

  

创建路线

Route::get('upgrade/createdBy','UpgradeController@upgradeCreatedBy')
  

创建UpgradeController

php artisan make:controller UpgradeController

在您的UpgradeControlller.php

Class UpgradeController
{
  public function upgradeCreatedBy()
  {

   // write your logic for find the admin_id and assign your variable to $adminId

    $stories = Stories::all();
    $count = 0; 
    foreach($stories as $story)
    {
      $story->update(['created_by'=> $adminId]);
      $count ++;
    }

     return "$count rows updated successfully";
  }
}
  

现在,在您的浏览器中,在不同的服务器上运行网址http://your_domain/upgrade/createdBy,您的代码将会升级。

注意:: 删除您的路由和方法,我建议保留控制器文件,但删除您在控制器中编写的方法。因此,您可以在将来使用此升级控制器,只需为不同类型的升级添加路由和方法。

这是我在多台服务器上进行任何数据库升级的方法。

相关问题