How to give foreign key reference of a table in another database?
See original GitHub issueEnvironment
Knex version: “^1.0.1” Database + version: MySql 8.0.23 OS: Ubuntu 20.04
Select applicable template from below. @smorey2
Feature discussion / request
- Explain what is your use case: I have two databases (sso, and items). I wish to create a migration to create a new table belonging to items database that have foreign keys referencing to a table(eg. users) in sso database.
I am using:
table.integer('user_id').unsigned();
table.foreign('user_id').references('sso.users.id');
This produce the error:
migration failed with error: alter table `group_sale_items` add constraint `group_sale_items_user_id_foreign` foreign key (`user_id`) references `sso`.`users` (`id`) - Referencing column 'user_id' and referenced column 'id' in foreign key constraint 'group_sale_items_user_id_foreign' are incompatible.
-
Explain what kind of feature would support this: It would be great to have a feature where we can specify the database too like we specify the table using inTable(‘users’).
-
Give some API proposal, how the feature should work: An API to which we can give database name and it will reference the table to that particular database’s table.
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (2 by maintainers)
Top GitHub Comments
I don’t know how to do cross-db references but with knex.raw you can pass any sql you want on it. I have no idea if it will work for your usecase.
By the way, this is not a knex issue.
@smorey2 I am using different knex configurations for different databases. I have a docker container for mysql dbs and I am giving cross-db references in my mysql dump, it do check for tables constraint and work well in the case. It is something similar to operate multiple microservices together.
@santialbo Could you give a specific example of using knex.raw in migration files for giving cross-db references so that it can check into a particular db and put up the constraint in another db.