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
- },
- somefield: {type: DataTypes.TEXT, unique: true}
- }, {
- timestamps: false,
- tableName: 'parents'
- });
- db.children = db.define('Child', {
- _id: {
- type: DataTypes.INTEGER,
- primaryKey: true,
- autoIncrement: true
- }
- }, {
- timestamps: false,
- tableName: 'children'
- });
- db.parentToChild = db.define('parentToChild', {
- parentId: {type: DataTypes.INTEGER},
- childId: {type: DataTypes.INTEGER},
- additional: {type: DataTypes.TEXT}
- }, {
- timestamps: false,
- tableName: 'parentToChild'
- });
- db.parents.belongsToMany(db.children, {
- as: 'children',
- through: 'parentToChild',
- foreignKey: 'parentId',
- otherKey: 'childId',
- timestamps: false
- });
- db.parents.hasMany(db.parentToChild, {
- as: 'additionals',
- foreignKey: 'parentId'
- });
- db.parentToChild.removeAttribute('id');
- db.parentToChild.belongsTo(db.children, {
- as: 'child',
- foreignKey: 'childId',
- targetKey: '_id'
- });
- (async () => {
- try {
- await db.transaction(async (transaction) => {
- await db.parents.truncate({transaction});
- await db.parentToChild.truncate({transaction});
- await db.children.truncate({transaction});
- const {_id: parentId} = await db.parents.create(
- {somefield: 'somevalue'},
- {transaction}
- );
- const {_id: childId} = await db.children.create({}, {transaction});
- await db.parentToChild.create({
- parentId,
- childId,
- additional: 'some additional info'
- }, {transaction});
- const parent = await db.parents.findOne({
- where: {somefield: 'somevalue'},
- include: [{
- model: db.parentToChild,
- as: 'additionals',
- required: true,
- include: [{
- model: db.children,
- as: 'child',
- required: true
- }]
- }],
- transaction,
- logging: console.log
- });
- console.log(require('util').inspect(parent.toJSON(), false, null));
- });
- } catch (err) {
- console.log(err.stack);
- }
- })();
Add Comment
Please, Sign In to add comment