Skip to content

Instantly share code, notes, and snippets.

@snewell92
Created June 2, 2017 16:01
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save snewell92/1d43bba7a50df0a143516ba86b37e49f to your computer and use it in GitHub Desktop.
Save snewell92/1d43bba7a50df0a143516ba86b37e49f to your computer and use it in GitHub Desktop.
Sequelize ES6 model syntax
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));
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' });
}
}
@chanlito
Copy link

chanlito commented Jun 8, 2017

does this actually work? cuz it's looking good.

@peterb0yd
Copy link

peterb0yd commented Jun 25, 2017

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.

@zhanwenchen
Copy link

@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.

@fraser71
Copy link

Thanks for this. Very useful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment