Skip to content

Instantly share code, notes, and snippets.

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 DesignByOnyx/2fe00cdc96312dda971020dd54ba84b6 to your computer and use it in GitHub Desktop.
Save DesignByOnyx/2fe00cdc96312dda971020dd54ba84b6 to your computer and use it in GitHub Desktop.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('postgres://db_user:db_pass@localhost:5432/findandcount-test', {
dialect: 'postgres'
});
const Property = sequelize.define('properties', {
name: {
type: Sequelize.STRING,
allowNull: false
}
}, {
freezeTableName: true
});
const Environment = sequelize.define('environments', {
name: {
type: Sequelize.STRING,
allowNull: false
}
}, {
freezeTableName: true
});
Property.associate = function (models) {
this.hasMany(models.environments);
};
Environment.associate = function(models) {
this.belongsTo(models.properties)
};
Object.keys(sequelize.models).forEach(modelName => {
if('associate' in sequelize.models[modelName]) {
sequelize.models[modelName].associate(sequelize.models);
}
});
sequelize.sync({ force: true })
.then(() => {
// No need to create environments
return Property.bulkCreate([{
name: 'Property 1'
}, {
name: 'Property 2'
}]);
})
.then(() => {
return Property.findAndCount({
include: [Environment],
raw: false // CHANGE THIS TO `TRUE` TO SEE A PROPER COUNT
});
})
.then(result => console.log(result))
.catch(err => console.log('Error:', err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment