Start typing to search
User.ts
import {
Model,
FindOptions,
DataTypes,
BelongsTo,
BelongsToGetAssociationMixin,
BelongsToSetAssociationMixin,
BelongsToCreateAssociationMixin,
} from 'sequelize'
import { sequelize } from '../connection'
export class User extends Model {
static associations: {
group: BelongsTo
}
id: number
username: string
firstName: string
lastName: string
createdAt: Date
updatedAt: Date
// mixins for association (optional)
groupId: number
group: UserGroup
getGroup: BelongsToGetAssociationMixin<UserGroup>
setGroup: BelongsToSetAssociationMixin<UserGroup, number>
createGroup: BelongsToCreateAssociationMixin<UserGroup>
}
User.init(
{
username: DataTypes.STRING,
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
},
{ sequelize }
)
// associate
// it is important to import _after_ the model above is already exported
// so the circular dependency works.
import { UserGroup } from './UserGroup'
User.belongsTo(UserGroup, { as: 'group', foreignKey: 'groupId' })
app.ts
import { User, Group } from './models/User'
async function test() {
const user = await User.findOne({ include: [Group] })
user.firstName = 'John'
await user.save()
await user.setGroup(2)
new User()
new User({ firstName: 'John' })
const user2 = await User.create({ firstName: 'John', groupId: 1 })
}