Skip to content

Instantly share code, notes, and snippets.

@MikeDabrowski
Last active March 18, 2018 08:37
Show Gist options
  • Save MikeDabrowski/e93b2dd41ab07849ec028425d41adf75 to your computer and use it in GitHub Desktop.
Save MikeDabrowski/e93b2dd41ab07849ec028425d41adf75 to your computer and use it in GitHub Desktop.
Sequelize m2m
import * as Sequelize from 'sequelize';
import { sequelize } from '../instances/sequelize';
export const Role = sequelize.define('roles', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
roleName: {
type: Sequelize.STRING,
unique: true
}
}, {
tableName: 'roles'
});
import { Body, ContentType, Delete, Get, JsonController, Param, Post, Req, Res } from 'routing-controllers';
import { User, UserModel } from '../models/user.model';
import { Role } from '../models/role.model';
@JsonController('/users')
export class UserController {
constructor(private userService: UserService) {
}
/* ... */
@Get('r/testr') // test function
testRole(@Res() response: express.Response) {
User.create({name: 'some user'}).then((user: any) => {
Role.create({roleName: 'some role'}).then((role: any) => {
user.setRoles([role]); // user.setRoles is not a function
});
});
return User.find({where: {username: 'Mike'}, include: [{model: Role}]});
}
}
import * as Sequelize from 'sequelize';
import { sequelize } from '../instances/sequelize';
export const User = sequelize.define('users', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: Sequelize.STRING,
}, {
tableName: 'users'
});
import * as DataTypes from 'sequelize';
import { sequelize } from '../instances/sequelize';
import { User } from './user.model';
import { Role } from './role.model';
export const UserRole = sequelize.define('users_role', {
role_id: {
type: DataTypes.INTEGER,
unique: 'user_role_roleable'
},
user_id: {
type: DataTypes.INTEGER
}
}, {
tableName: 'users_roles'
});
User.belongsToMany(Role, {
through: 'users_roles'
});
Role.belongsToMany(User, {
through: 'users_roles'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment