0

In the Models of a many to many relationship I have accidentally identified the foreign key names in reverse. This is done in both related Models so the relationship works. It's in production.

In Articles:

public function categories()
{
    return $this->belongsToMany(ArticleCategory::class, 'article_category_article', 'article_category_id', 'article_id');
}

and in ArticleCategory:

public function articles()
{
    return $this->belongsToMany(Article::class, 'article_category_article', 'article_id', 'article_category_id');
}

As you can see, both foreign keys are reversed.

It doesn't bother me because it works throughout the project. In the article_category_article table both values are recorded in the 'wrong' column.

But what if I'd like to swap it anyway. The Models are easy, but what about the pivot table? I have tried with a laravel migration:

public function up()
{
    Schema::table('article_category_article', function (Blueprint $table) {
        $table->renameColumn('article_id', 'temporarily');
        $table->renameColumn('article_category_id', 'article_id');
        $table->renameColumn('temporarily', 'article_category_id');
    });
}

without success, it predictably runs into the error There is no column with name 'temporarily' on table 'article_category_article'

Splitting it up in 2 migration files ran into the same error.

I have the tendency to let it be. The question is: can it be done? I presume swapping the columns inside MySQL (without migrations), re-index the tables and adapt the Models is a possibility. Any ideas? I can test it out on a local server.

Dimitri Mostrey
  • 2,302
  • 1
  • 12
  • 11

1 Answers1

1

Two separate queries work for me:

public function up()
{
    Schema::table('article_category_article', function (Blueprint $table) {
        $table->renameColumn('article_id', 'temporarily');
        $table->renameColumn('article_category_id', 'article_id');
    });
    Schema::table('article_category_article', function (Blueprint $table) {
        $table->renameColumn('temporarily', 'article_category_id');
    });
}
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109