sequelize-typescript .$set doesn't set hasMany relationship

Viewed 35

I have these two models:

@Table
export class Role extends Model {
    @PrimaryKey
    @Column({type: DataType.UUID, defaultValue: DataType.UUIDV4})
    declare id: string

    @Column
    name: string

    @Column
    account_id: string

    @CreatedAt
    created_at: Date

    @UpdatedAt
    updated_at: Date

    @HasMany(() => RolePermission, {foreignKey: 'role_id'})
    permissions: RolePermission[]
}


@Table({tableName: 'role_permission'})
export class RolePermission extends Model {
    @PrimaryKey
    @Column({type: DataType.UUID, defaultValue: DataType.UUIDV4})
    declare id: string

    @Column
    permission: string

    @CreatedAt
    created_at: Date

    @UpdatedAt
    updated_at: Date

    @BelongsTo(() => Role, {foreignKey: 'role_id'})
    role: Role
}

I am trying to update the role and SET the role's permissions. The permissions is just a list of strings. There isn't a model for permissions. I tried this:


const form = {
    name: 'role name here' 
    permissions: ['home.view']
}

const role = await Role.findByPk(id)
if(!role){
    throw new Error("role not found")
}
await role.update({
    name: form.name,
})
await role.$set('permissions', form.permissions.map(permission => RolePermission.build({permission})))

It sets the role's name but it doesn't update the role's permissions in the database. The old permissions from the create code below are still there. No errors occur.

PS. Creating a role with permissions works correctly:

const form = {
    name: 'role name here' 
    permissions: ['home.view']
}
const role = await Role.create({
    account_id: request.account,
    name: form.name,
    permissions: form.permissions.map(permission => ({permission}))
}, {
    include:[RolePermission]
})

On solution that ALMOST works is this:

await RolePermission.bulkCreate(form.permissions.map(permission => ({permission, role_id: role.id})))

But for this I need to clear the old permissions and I can't seem to do that:

Attemp 1:

await role.$set('permissions', []) // gives DEADLOCK SQL error

Attemp 2:

role.permissions = []
await role.save() // doesn't do anything

How is it possible to set a model's HasMany relationship with new rows (and remove the old ones)?

0 Answers
Related