Skip to content

Instantly share code, notes, and snippets.

@psixdev
Last active June 8, 2018 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psixdev/fe26a976bde0893ddeb2d7745ff4fa51 to your computer and use it in GitHub Desktop.
Save psixdev/fe26a976bde0893ddeb2d7745ff4fa51 to your computer and use it in GitHub Desktop.
Sequelize bug 2
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);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment