-
-
Save rachmadideni/4671b14d92d279700a5edb5863625a84 to your computer and use it in GitHub Desktop.
TypeORM ManyToMany relation with custom pivot table and column names.
This file contains hidden or 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 hidden or 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 hidden or 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