Created
June 2, 2017 16:01
-
-
Save snewell92/1d43bba7a50df0a143516ba86b37e49f to your computer and use it in GitHub Desktop.
Sequelize ES6 model syntax
This file contains 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
var Promise = require('bluebird'); | |
const Sequelize = require('sequelize'); | |
const fs = Promise.promisifyAll(require('fs')); | |
const _ = require('lodash'); | |
const sequelize = new Sequelize(connectionString, { | |
dialect: 'mysql', | |
logging: false, | |
pool: { // application-side connection pool configuration | |
max: 1000, | |
min: 0, | |
idle: 50000 | |
} | |
}); | |
// Load all models | |
await fs.readdirAsync('./src/models') | |
.map(fileName => { | |
// ?? With ES6 should I System.import('./models/' + fileName)? | |
let model = require('./models/' + fileName); | |
/* NEW es6 style...? */ | |
if(model.init) { | |
model.init(sequelize); | |
} else { | |
model(sequelize, Sequelize); | |
} | |
}); | |
// associate | |
const models = sequelize.models; | |
_.map(Object.keys(models), n => models[n]) | |
.filter(m => m.associate !== undefined) | |
.forEach(m => m.associate(models)); |
This file contains 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
import { Model, DataTypes } from 'sequelize'; | |
export class User extends Model { | |
static init(sequelize) { | |
super.init({ | |
username: { | |
type: DataTypes.STRING, | |
unique: true, | |
allowNull: false | |
}, | |
firstname: DataTypes.STRING, | |
lastname: DataTypes.STRING, | |
password: { | |
type: DataTypes.STRING, | |
allowNull: false | |
}, | |
email: { | |
type: DataTypes.STRING, | |
unique: true, | |
allowNull: false | |
}}, { | |
sequelize | |
} | |
); | |
} | |
static associate(sequelize) { | |
this.belongsToMany(sequelize.Models.Role, { through: 'userroles' }); | |
} | |
} |
I've tried implementing this 15,000 different ways and none of them work. Please, someone put up a working example of this. I think the OP put this up as a nice-to-have.
@BruceHem @peterb0yd I have a working example in this comment which is drawn from my blog repo.
You just need to replace the new Sequelize()
variables with your own in index.js
.
Thanks for this. Very useful
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
does this actually work? cuz it's looking good.