Skip to content

Instantly share code, notes, and snippets.

@psixdev
Last active June 5, 2018 12:02
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/09d35df41e8dc9702c4d9c85e3092b87 to your computer and use it in GitHub Desktop.
Save psixdev/09d35df41e8dc9702c4d9c85e3092b87 to your computer and use it in GitHub Desktop.
Sequelize bug
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);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment