Last active
August 21, 2019 00:11
-
-
Save DesignByOnyx/2fe00cdc96312dda971020dd54ba84b6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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