Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const Sequelize = require('sequelize');
- const config = require('./config')();
- const {DataTypes} = Sequelize;
- const db = new Sequelize({
- database: config.postgres.database,
- username: config.postgres.user,
- password: config.postgres.password,
- host: config.postgres.host,
- port: config.postgres.port,
- dialect: 'postgres',
- logging: false
- });
- db.parents = db.define('Parent', {
- _id: {
- type: DataTypes.INTEGER,
- primaryKey: true,
- autoIncrement: true
- }
- }, {
- timestamps: false,
- tableName: 'parents'
- });
- db.somethings = db.define('Something', {
- _id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true}
- }, {
- timestamps: false,
- tableName: 'somethings'
- });
- db.children = db.define('Child', {
- _id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
- parentId: DataTypes.INTEGER,
- somethingId: DataTypes.INTEGER
- }, {
- timestamps: false,
- tableName: 'children'
- });
- db.parents.hasMany(db.children, {
- as: 'children',
- foreignKey: 'parentId'
- });
- db.somethings.hasMany(db.children, {
- as: 'children',
- foreignKey: 'somethingId'
- });
- db.children.belongsTo(db.parents, {
- as: 'parent',
- foreignKey: 'parentId',
- targetKey: '_id'
- });
- db.children.belongsTo(db.somethings, {
- as: 'something',
- foreignKey: 'somethingId'
- });
- (async () => {
- try {
- await db.transaction(async (transaction) => {
- await db.parents.truncate({transaction});
- await db.somethings.truncate({transaction});
- await db.children.truncate({transaction});
- const {_id: parentId} = await db.parents.create({}, {transaction});
- const {_id: somethingId} = await db.somethings.create({}, {transaction});
- await db.children.bulkCreate(
- [{parentId, somethingId}, {parentId, somethingId}],
- {transaction}
- );
- const parents = await db.parents.findAll({
- include: [{
- model: db.children,
- as: 'children',
- required: true,
- include: [{
- model: db.somethings,
- as: 'something',
- required: true
- }]
- }],
- limit: 5,
- transaction,
- logging: console.log
- });
- console.log(
- require('util').inspect(
- parents.map((parent) => parent.toJSON()),
- false,
- null
- )
- );
- });
- } catch (err) {
- console.log(err.stack);
- }
- })();
Add Comment
Please, Sign In to add comment