'How to put a foreign key in knex migration?
I'm trying to put a foreign key in knex migration. "age_group_id"(primary key of the "agegroups" table) is the foreign key of the "users" table. So, I have put it like the below picture. (line 22)
20220424203501_create_users.ts
When I run the code (npm run deploy:fresh) it shows an error like the below.
But, without line number 22, it is not showing an error. Here is my folder structure.
Can someone help me to fix this issue and what is wrong with the way I wrote the foreign key?
Solution 1:[1]
You need to use the same data type in both tables when using foreign keys. As an example, if you are using 'uuid' for id in agegroups table, then you must use uuid for users table foreign key (age_group_id)also. But here you used 'text' data type for foreign key. Please check whether both data types are similar or not.
Solution 2:[2]
you should check if your database has data that doesn't fit like an id value that is not present in the foreign table, delete any rows like that and the migration should work, it would help if you let us know what npm run deploy:fresh
does, you might be doing something else wrong if the data is not clearing on a clean migration
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wanuja Ranasinghe |
Solution 2 | M-Raw |