Reputation: 81
When retrieving parent entity "User", i can add and update the one-to-many related entities "AdminUserGroup". But when the child entities "AdminUserGroup" are removed from the parent "User", nothing happens.
The Foreign keys in child object are not set to null and nor the records are deleted.
I am using postgres as database.
Child entities Removing Method
async updateUserAdmin(data: UpdateUserAdminDto): Promise<User> {
var user = await this.findById(data.userId);
user.userGroups = null
//i have also tried
//user.userGroups = []
return await this.userRepository.save(user);
}
parent entity
@Entity({name: 'users'})
class User implements IUser {
@PrimaryGeneratedColumn()
id: number
@Column()
companyId: number
@Column()
privilegeId: number
@OneToMany(
() => AdminUserGroup,
(userGroup) => userGroup.user, { cascade: true })
userGroups: AdminUserGroup[]
}
Child entity
@Entity({ name: 'admin_cost_centers' })
class AdminUserGroup {
@PrimaryGeneratedColumn()
id: number
@ManyToOne(() => User, (user) => user.userGroups, orphanedRowAction: 'delete')
@JoinColumn()
user: User
@ManyToOne(() => Group, (group) => group.userGroups, orphanedRowAction: 'delete')
@JoinColumn()
group: Group
@Column()
startedAt: Date
}
Upvotes: 2
Views: 3082
Reputation: 79
The cascade action onDelete: CASCADE
causes the children to be deleted if the parent is deleted. Since you're not deleting the parent itself but nullify the reference in the respective child entities, cascades don't apply.
Since version 0.2.33 typeorm supports the orphanedRowAction
on child entities which lets you specify what should happen if the reference is about to be removed:
@Entity({ name: 'admin_cost_centers' })
class AdminUserGroup {
@PrimaryGeneratedColumn()
id: number
@ManyToOne(() => User, (user) => user.userGroups, {
// The 'delete' action causes the user group to be deleted
// if it is no longer mapped to a user
orphanedRowAction: 'delete'
})
@JoinColumn()
user: User
@Column()
startedAt: Date
}
Upvotes: 3