Encountered an error with knex and MYSQL js: ER_CANNOT_ADD_FOREIGN - Unable to establish foreign key constraint

Having trouble with knex migrate:latest. Here's the error:

migration file "20200701012817_personal_todos.ts" failed
migration failed with error: alter table `personal_todos` add constraint `personal_todos_board_id_foreign` foreign key (`board_id`) references `personal_todo_board` (`id`) on update CASCADE on delete CASCADE - ER_CANNOT_ADD_FOREIGN: Cannot add foreign key constraint
I am attempting to create a table with two foreign keys from different tables - users and todos. While the user foreign key works fine, adding the other one results in the above error. Any suggestions would be appreciated! Additionally, Knex is installed in node_modules... The code snippet provided below is related, but not exactly the same as the issue being faced.

KNEX & MYSQL - Error: ER_CANNOT_ADD_FOREIGN: Cannot add foreign key constraint.
Unfortunately, the solution offered there did not work for my case...

User Table:

    import * as Knex from "knex";
    
    
    export async function up(knex: Knex): Promise<any> {
        return knex.schema.createTable('users', (table)=>{
            table.increments('id').primary();
            table.string('first_name');
            table.string('last_name');
            table.string('username').notNullable();
            table.string('email');
            table.string('password').notNullable();
            table.integer('age');
            table.string('bio');
            table.string('gender');
            table.string('personalsecret1');
            table.string('personalsecret2');
            table.string('personalsecret3');
            table.binary('img');
            table.string('colorScheme');
            table.timestamps(true,true);
            table.boolean('payed');
            table.boolean('active');
            table.boolean('friends_can_see_private');
        })
    }
    
    
    export async function down(knex: Knex): Promise<any> {
        return knex.schema.dropTableIfExists('users')
    }

Todos Table Issue:

    import * as Knex from "knex";
    
    export async function up(knex: Knex): Promise<any> {
        return knex.schema.createTable('personal_todos', (table)=>{
            table.increments('id').primary();
            // Tried unsigned, didn't work
            table.integer('user_id').unsigned().notNullable();
            table.integer('board_id').unsigned().notNullable();
    
            table.foreign('user_id').references('users.id');
            // The problematic line below causing error
            // table.foreign('board_id').references('id').inTable('personal_todo_board').onUpdate('CASCADE').onDelete('CASCADE');
            
            table.boolean('active').notNullable();
            table.string('start_time');
            table.string('end_time');
            table.string('header');
            table.string('body');
            table.integer('container_index').notNullable();
            table.integer('container_item_index');
            table.timestamps(true,true);
            table.boolean('private').notNullable();
        })
    }
    
    
    export async function down(knex: Knex): Promise<any> {
        return knex.schema.dropTableIfExists('personal_todos');
    }

Board Table:

    import * as Knex from "knex";
    
    export async function up(knex: Knex): Promise<any> {
        return knex.schema.createTable('personal_todo_board', (table)=>{
            table.increments('id').primary();
            table.integer('user_id').unsigned().notNullable();
            table.foreign('user_id').references('users.id').onUpdate('CASCADE').onDelete('CASCADE');
            table.string('header').notNullable();
            table.string('last_active');
            table.string('small_description');
            table.timestamps( true, true);
            table.boolean('private').notNullable();
        })
    }
    
    
    export async function down(knex: Knex): Promise<any> {
        return knex.schema.dropTableIfExists('personal_todo_board')
    }

Answer №1

After some investigation, I discovered that the issue resided in how the files were created. Knex constructs each table based on the order of the js knex migrate:make table_name command you execute.

This implies that you must adhere to the sequence when referencing other tables. If you reference a table that has not been created yet, you will encounter a foreign key constraint error. In case this happens, duplicate the subsequent table with the foreign key, delete the original file, create a new one using js knex migrate:make table_name , and paste the content from the old table. Repeat this process for seed data if necessary. Remember to rollback, drop, and recreate your database to ensure everything is in proper order!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to retrieve data as a dictionary instead of a tuple using MySQL's fetchall() method

I have a table with the columns id, col1, col2, and col3. When I ran the query, this is how it was executed: cur.execute(query) row = cur.fetchall() Is there a way to store the data in the variable row inside a dictionary so that I can pass this result t ...

Save MySQL information to a CSV document

Hello, I am currently working on exporting data from a MySQL database to a CSV file and ensuring it is available for download in .csv format. Below is the code I am using: <?php if(isset($_GET['Download'])) { include 'conn.php'; ...

Establishing a connection to a local database while the docker container is active

Currently, I have been utilizing an app within a docker container. Previously, I had successfully connected Sequel Pro to my local DB. However, after reinstalling Sequel Pro, I have been facing difficulties reconnecting to my local DB. I have attempted t ...

Node.js is throwing the error "error TS18003: Config file does not contain any inputs."

I'm encountering an error and need help fixing it. Currently, I am using Windows 11. Every time I attempt to run npm run build in the command prompt, I encounter this specific error: Error File package.json package.json File tsconfig.json "com ...

Generating a list from a MySQL database table

I'm currently working on creating an array for use with curl_multi_exec, but I seem to be having trouble generating the array correctly. Below is the code I am using: $SQL = mysql_query("SELECT url FROM urls") or die(mysql_error()); //Query ...

received TypeError when using combineLatest

import { combineLatest } from 'rxjs'; const obs1 = getAndCreateObservableOne(); const obs2 = getAndCreateObservableTwo(); console.log('Initial output', obs1, obs2); obs1.subscribe(e => console.log('Second output', e)); o ...

Zend: Designing models for a items database

In the process of developing two distinct models, namely products and product_manufacturers, I aim to streamline the retrieval and modification of manufacturers and products through the admin interface. The blueprint for these tables is outlined below (sub ...

How to restrict MySQL select results by recurring column values?

Take a look at this database schema: create table Worker( id integer, name varchar(100), title varchar(100), department_id integer ); create table Wage( worker_id integer, year integer, month integer, salary float ); ...

Guide to making a Material Design Radial effect animation

I am looking to create a unique toolbar effect by following the material design radial reaction choreography guideline. https://i.stack.imgur.com/6oB8r.gif I want to achieve this using an angular 2 transition, but I need some guidance on how to implement ...

Using TypeScript to create a function with an argument that is optional based on a condition

I need a function that will only take a second argument when certain conditions are met. let func = <T extends boolean>(arg1: T, arg2: T extends true ? void : string) => {}; func(true); // ERROR Expected 2 arguments, but got 1 func(true, undefin ...

Update all entries in the website column by prefixing them with "http://"

Currently in the final stages of migrating/rebuilding a large mysql database for a new application. The 'website' column currently displays 'www.example.com'. However, because the new application interprets it as a hyperlink, I require ...

How can I correctly omit this particular group from my MySQL Query?

Table 1: Members | profile_id | name | ------------------------ | 1 | Sam | | 2 | Sarah | | 3 | Sydney | | 4 | Steven | Table 2: Member and Position to Project Lookup | project_id | profile_id | position ...

Failing to reach the nested if statements within a switch case block

Before removing my question, please read this. Despite testing with console.logs, my code does not enter the if statements. I have not come across a similar solution to my issue. In an attempt to address any timing or asynchronous problems, I added a use ...

Is there a way to integrate a MySQL database with parcel-bundler in a Node.js environment, or is there a simpler method to achieve this database integration with parcel-bundler?

Node.js and parcel-bundler are new to me, but I've managed to create a server.js file that connects to the database without any issues. Server.js const express = require('express'); const mysql = require('mysql'); //Establish con ...

Developers can leverage Node4 and Gulp to seamlessly integrate TypeScript with EcmaScript2015 in their

When converting TypeScript to ES2015, I encounter the need for async/await functionality. However, I must then convert the ES2015 code to be compatible with Node4, which does not fully support ES2015 features. The issue arises when using TypeScript defini ...

What could be the reason for MySQL database returning an empty ResultSet even though the data is accurate?

Situation: I'm dealing with two tables within my database. One is the actionblock table, which corresponds to the ActionBlock class in Java, and the other is the location table, which corresponds to PermanentLocation class in Java. The ActionBlock cl ...

Checking the mysql database every 10 seconds to detect any new rows

I am currently working on a php chat application and have begun the process of checking the database using PHP. I am looking for a way to continuously check the database every 10 seconds so that users can see new messages from others in real-time. While I ...

Implementing the react-i18next withNamespaces feature in Ant Design forms

I'm a newcomer to i18next and TypeScript, and I'm trying to translate an antd form using withNamespaces. export default withNamespaces()(Form.create()(MyComponent)); Encountering the following error: Argument of type 'ComponentClass< ...

Issue with data type not refreshing in mySQL Workbench

I'm facing an issue with changing the datatype of my "first_name" column. I want it to be VARCHAR(45), but it's stuck at INT(11) as shown in the table diagram and connection provided below. https://i.sstatic.net/0CbkD.png https://i.sstatic.net/8 ...

The child object in Typescript is characterized by its strong typing system

Looking to convert plain AngularJS code to Typescript? Take a look at this example: app.someController = function ($scope) { // var $scope.Data = null; var $scope.Data: SomeCollection = null; I need to associate Data with scope and specify it as type ...