【问题标题】:Adding a column with foreign key添加具有外键的列
【发布时间】:2017-06-16 01:43:56
【问题描述】:

我现有的表格如下所示

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

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

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

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

我想在我的 PC、测试机、实时服务器中进行此修改。所以我必须添加外键,还必须从用户表中找出管理员 ID 并分配给它。如何做到这一点?

【问题讨论】:

  • 您的 admin_id 是如何与故事表关联的?
  • 管理员也是用户之一,他可以添加故事..我只是对表格设计给出了一个粗略的想法。
  • 我想知道 admin_id 与您的新专栏 created_by 的关系。我的意思是有些 author_id 也是 admin_id 吗?您想将 created_by 分配给那些是 admin 的作者吗?
  • 没有。作者和创建者是不同的。作者 id 用于前端。例如:Chethan Bhagath 可能是作者,但 created_by 会告诉您谁在我们的 Web 应用程序中制作了这个故事。 created_by 用于后端团队
  • 好的。我了解,但您有任何数据可以用来填充现有故事的 created_by 吗?。

标签: php laravel laravel-5 laravel-5.3


【解决方案1】:

使用@Eric Tucker 回答创建迁移

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

创建路线

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

创建升级控制器

php artisan make:控制器升级控制器

在您的 UpgradeController.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";
  }
}

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

注意::删除你的路由和方法,我建议保留控制器文件但删除你在控制器中编写的方法。这样你以后就可以通过添加不同类型升级的路由和方法来使用这个升级控制器了。

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

【讨论】:

    【解决方案2】:

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

    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');
        });
    }
    

    【讨论】:

    • 这个我理解,但我必须从 users 表中获取管理员 ID 并分配给它
    • 您是说在运行迁移时用表上已有的author_id 列填充该列吗?
    • 是的。添加该列后,我们必须从用户表中搜索“管理员”,并且我们必须填写故事表中的旧条目
    • Admin 表与 Story 表的当前关系是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2013-07-12
    • 2019-04-13
    • 2017-04-03
    • 2011-08-01
    • 1970-01-01
    相关资源
    最近更新 更多