Last active
September 27, 2024 19:33
-
-
Save victorcrbt/d6f376635bfb65484936d75e7e6959ac to your computer and use it in GitHub Desktop.
TypeORM ManyToMany relation with custom pivot table and column names.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable } from 'typeorm'; | |
import Company from './Company'; | |
@Entity('clients') | |
export default class Client { | |
@PrimaryGeneratedColumn() | |
id: number; | |
@Column() | |
name: string; | |
@Column() | |
email: string; | |
@Column() | |
document: string; | |
@Column() | |
password: string; | |
@ManyToMany(() => Company, company => company.clients) | |
@JoinTable({ | |
name: 'clients_companies_relation', | |
joinColumn: { | |
name: 'client_id', | |
referencedColumnName: 'id', | |
}, | |
inverseJoinColumn: { | |
name: 'company_id', | |
referencedColumnName: 'id', | |
} | |
}) | |
companies: Company[]; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { getRepository, Repository } from 'typeorm'; | |
import Client from '../entities/Client'; | |
interface IClientsRepository { | |
findById(id: number): Promise<Client>; | |
} | |
export default class ClientsRepositoryimplements IClientsRepository { | |
private ormRepository: Repository<Client>; | |
constructor() { | |
this.ormRepository = getRepository(Client); | |
} | |
public async findById (id: number): Promise<Client> { | |
const client = await this.ormRepository.findOne(id, { relations: ['companies'] }); | |
return client; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Entity, PrimaryGeneratedColumn, Column, ManyToMany } from 'typeorm'; | |
import Client from './Client'; | |
@Entity('companies') | |
export default class Company { | |
@PrimaryGeneratedColumn() | |
id: number; | |
@Colum() | |
company_name: string; | |
@Column() | |
document: string; | |
@Column() | |
phone: string; | |
@ManyToMany(() => Client, client => client.companies) | |
clients: Client[]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing!