Created
August 20, 2019 14:02
-
-
Save foysalit/a3176c3d588b27606a0d3a064fd56970 to your computer and use it in GitHub Desktop.
Sequelize Cross database join example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Sequelize = require('sequelize'); | |
const sequelizeConfig = { | |
username: "root", | |
password: "admin", | |
dialect: "mysql" | |
}; | |
const userDb = new Sequelize({...sequelizeConfig, database: 'sequelize_test_users'}); | |
const contentDb = new Sequelize({...sequelizeConfig, database: 'sequelize_test_contents'}); | |
const User = userDb.define('user', { | |
username: Sequelize.STRING, | |
birthday: Sequelize.DATE, | |
}); | |
const Post = contentDb.define('post', { | |
title: Sequelize.STRING, | |
body: Sequelize.TEXT, | |
user_id: Sequelize.INTEGER, | |
}); | |
(async () => { | |
await userDb.sync(); | |
await contentDb.sync(); | |
User.hasMany(Post, { foreignKey: 'user_id' }); | |
Post.belongsTo(User, { foreignKey: 'user_id' }); | |
const user = await User.create({username: 'foysal', birthday: '01-01-2001'}); | |
const postOne = await Post.create({title: 'test post one', body: 'this is post content', user_id: user.id}); | |
const postTwo = await Post.create({title: 'test post two', body: 'this is post content', user_id: user.id}); | |
const userWithPosts = await User.findOne({ | |
include: [{ | |
model: Post | |
}] | |
}); | |
console.log(userWithPosts); | |
await user.destroy(); | |
await postOne.destroy(); | |
await postTwo.destroy(); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "sequelize-cross-db-example", | |
"version": "1.0.0", | |
"description": "sequelize example showing cross db join", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"mysql2": "^1.6.5", | |
"sequelize": "git+https://[email protected]/foysalit/sequelize.git" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment