A user can create as many organizations as they like. An organization can contain multiple users. A user can have only one role in an organization, but they can have another role in a different organization. An organization can have multiple users for one role. The user is the main table, so the JoinTable decorator should be in the user entity.
I tried by creating following entities.
This is User entity
import {
Entity,
Column,
PrimaryGeneratedColumn,
ManyToMany,
JoinTable,
ManyToOne,
} from 'typeorm';
import { Role, Organizations } from '@models';
@Entity({ name: 'users' })
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
email: string;
@Column({ nullable: true, select: false })
password: string;
@Column({ default: false })
active: boolean;
@ManyToOne(() => Role, (role) => role.user, { cascade: true })
role: Role;
@ManyToMany(() => Organizations, (orgnizations) => orgnizations.user, {
cascade: true,
})
@JoinTable({
name: 'user_organization',
})
organization: Organizations[];
}
This is Organization entity
import { Entity, Column, PrimaryGeneratedColumn, ManyToMany } from 'typeorm';
import { User } from '@models';
@Entity({ name: 'organizations' })
export class Organizations {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
type: string;
@Column()
size: number;
@ManyToMany(() => User, (user) => user.organization)
user: User[];
}
This is Role entity
import {
Column,
Entity,
ManyToMany,
ManyToOne,
OneToMany,
PrimaryGeneratedColumn,
} from 'typeorm';
import { User } from '@models';
@Entity({ name: 'roles' })
export class Role {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@ManyToOne(() => User, (user) => user.role)
user: User[];
}
But by this entity user_organization
table contains only user_id
and organization_id
. But I want this table contain role_id
as well so that I can store user by their role in specific organization. What should I do? I’m new to typeORM please help.