Reputation: 334
Please find below code sample of two table book and author and I want to list all books alongs with author detail,
Book
@Entity()
export class Book{
@PrimaryKey()
id!: number;
@Property()
title!: string;
@ManyToOne({ entity: () => Author }) // or use options object
author!: Author;
}
Author:
@Entity()
export class Author {
@PrimaryKey()
id!: number;
@Property()
createdAt: Date = new Date();
@Property({ onUpdate: () => new Date() })
updatedAt: Date = new Date();
@Property()
name!: string;
@Property()
email!: string;
@Property({ nullable: true })
age?: number;
@Property({ nullable: true })
identities?: string[];
@Property({ nullable: true })
born?: Date;
@OneToMany({ entity: () => Book, mappedBy: 'author', orphanRemoval: true })
books = new Collection<Book>(this);
@Property({ version: true })
version!: number;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
Service:
@Injectable()
export class AppService {
constructor(
private readonly orm: MikroORM,
private readonly em: EntityManager,
) {}
async findBooks(): Promise<any> {
const books: Book[] = await this.orm.em.find(Book, {});
return books;
}
}
Currently I am getting result like: Ref { id: 4 } but I want to get all author detail along with id.
Please correct in service page if possible.
Upvotes: 1
Views: 1060
Reputation: 531
You can populate all relationships by passing populate: true
Like:
const result = await this.bookRepository.findAll({ populate: true });
This will return list of all the books with populated author details.
EDIT:
If you are using an EntityManager, then you can use it like this:
const books: Book[] = await this.orm.em.find(Book, {}, { populate: true });
Upvotes: 1