Skip to content

Latest commit

 

History

History
92 lines (75 loc) · 2.91 KB

docs_index.md

File metadata and controls

92 lines (75 loc) · 2.91 KB

Start typing to search

API

Associations

Example

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 })
}