Cross-Database Associations in Sequelize ORM
Don’t create two or more separate queries when it’s possible to use one
At some point, I think I pretty much became a pro at it and was able to do absolutely anything that was required, except one thing — cross-database joints.
It was a huge struggle for me as some of the applications used multiple databases and some queries required to get associated data from several of them. There are a lot of topics on Stack Overflow and GitHub Issues, but none of them had exact steps to make it work.
For a long time, I had to write queries manually, executing them with
It’s been working fine for me, especially combining them with model hooks, but it’s always bothered me having to make two or more separate queries, when it’s possible to use one.
Let’s look at some code. Let’s say, we have two databases: one containing users and orders, another one containing products. Users can have multiple orders and orders can have multiple products:
Let’s create two Sequelize database connection instances:
And set up some associations:
Now, we can use autogenerated model methods to create and view products that belong to a specific order:
However, if we are going to try to use the
include option, we’re going to hit the following error
Let’s go ahead and fix that.
The first thing you need to do is to manually adjust the Sequelize database connection instance, like so:
Then, add the schema name to the product model options:
Lastly, you need to manually update the association scope, as the default association is still going to try to hit the
Bingo! Now you can create multiple complex queries using tables from different databases.
Make sure you use the literal string representation if you want to do deeper nesting, like so: