1 | initial version |
To perform an outer join in a many-to-many relation using TypeORM, you can use the leftJoinAndSelect
function to join two tables and select all entities from one table and matching entities from another. Here's an example:
@Entity()
class Book {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@ManyToMany(() => Author, author => author.books)
authors: Author[];
}
@Entity()
class Author {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@ManyToMany(() => Book, book => book.authors)
books: Book[];
}
const books = await getRepository(Book)
.createQueryBuilder('book')
.leftJoinAndSelect('book.authors', 'author')
.orderBy('book.id')
.getMany();
console.log(books);
In this example, we're joining the Book
and Author
tables using the @ManyToMany
decorator, creating an outer join that selects all books and their matching authors. We're then using the leftJoinAndSelect
function on the Book
repository to perform this join, and ordering the results by the book ID. The output will be an array of books, each with an array of authors.