Loading objects with their relations
Now let’s load our photo and its photo metadata in a single query.There are two ways to do it - using find*
methods or using QueryBuilder
functionality.Let’s use find*
methods first.find*
methods allow you to specify an object with the FindOneOptions
/ FindManyOptions
interface.
import {createConnection} from "typeorm";
import {Photo} from "./entity/Photo";
import {PhotoMetadata} from "./entity/PhotoMetadata";
createConnection(/*...*/).then(async connection => {
/*...*/
let photoRepository = connection.getRepository(Photo);
let photos = await photoRepository.find({ relations: ["metadata"] });
}).catch(error => console.log(error));
Here, photos will contain an array of photos from the database, and each photo will contain its photo metadata.Learn more about Find Options in this documentation.
Using find options is good and dead simple, but if you need a more complex query, you should use QueryBuilder
instead.QueryBuilder
allows more complex queries to be used in an elegant way:
import {createConnection} from "typeorm";
import {Photo} from "./entity/Photo";
import {PhotoMetadata} from "./entity/PhotoMetadata";
createConnection(/*...*/).then(async connection => {
/*...*/
let photos = await connection
.getRepository(Photo)
.createQueryBuilder("photo")
.innerJoinAndSelect("photo.metadata", "metadata")
.getMany();
}).catch(error => console.log(error));
QueryBuilder
allows creation and execution of SQL queries of almost any complexity.When you work with QueryBuilder
, think like you are creating an SQL query.In this example, “photo” and “metadata” are aliases applied to selected photos.You use aliases to access columns and properties of the selected data.