0

I'm trying to run my migrations but keep getting the following error.

 SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `votes` add constraint `votes_topic_id_foreign` foreign key (`topic_id`) references `voting_topic_results` (`division_id`))

I have tried both solutions in this post with no joy.

My two migration files are:

voting_topic_results

public function up()
{
    Schema::create('voting_topic_results', function (Blueprint $table) {
        $table->id();
        $table->integer('division_id');
        $table->dateTime('date');
        $table->string('title');
        $table->string('description')->nullable();
        $table->integer('aye_count');
        $table->integer('noe_count');
    });
}

votes

public function up()
{
    Schema::create('votes', function (Blueprint $table) {
        $table->id();
        $table->integer('topic_id');
        $table->foreign('topic_id')->references('division_id')->on('voting_topic_results');
        $table->integer('user_id');
        $table->foreign('user_id')->references('id')->on('users');
        $table->integer('user_aye_count')->nullable();
        $table->integer('user_noe_count')->nullable();
        $table->unique(['topic_id', 'user_id']);
    });
}

EDIE***

I've updated my code to what the related question was referring to and I'm still getting the same error.

CIB
  • 535
  • 1
  • 12
  • 35
  • If have have declared the relationships in your models, just avoid adding the foreign keys in the schema – Ahmad Karimi Feb 01 '21 at 09:05
  • The duplicate question gives you the exact answer. However, the canonical answer contsining all possible causes for this error messsge is in the following SO question: https://stackoverflow.com/questions/1457305/mysql-creating-tables-with-foreign-keys-giving-errno-150 – Shadow Feb 01 '21 at 09:06
  • In your `voting_topic_results` schemas, your `division_id` column isn't the same type as your declaration in `votes`. `$table->integer('division_id')->unique();` is not equal to `$table->integer('topic_id')->unsigned();` that's why the error occurs. After correction, check that your `voting_topic_results` schemas migrate before `votes`. – Atika Feb 01 '21 at 09:18
  • @Atchiiii i've just removed the ```->unique()``` & ```->unsigned()``` and it's still giving the same error – CIB Feb 01 '21 at 09:46
  • @CIB verify that you are migrating the `voting_topic_results` schema before `votes`. – Atika Feb 01 '21 at 10:19
  • @Atchiiii yeah the ```voting_topic_results``` is run first – CIB Feb 01 '21 at 10:27

0 Answers0