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.

  1. import {createConnection} from "typeorm";
  2. import {Photo} from "./entity/Photo";
  3. import {PhotoMetadata} from "./entity/PhotoMetadata";
  4. createConnection(/*...*/).then(async connection => {
  5. /*...*/
  6. let photoRepository = connection.getRepository(Photo);
  7. let photos = await photoRepository.find({ relations: ["metadata"] });
  8. }).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:

  1. import {createConnection} from "typeorm";
  2. import {Photo} from "./entity/Photo";
  3. import {PhotoMetadata} from "./entity/PhotoMetadata";
  4. createConnection(/*...*/).then(async connection => {
  5. /*...*/
  6. let photos = await connection
  7. .getRepository(Photo)
  8. .createQueryBuilder("photo")
  9. .innerJoinAndSelect("photo.metadata", "metadata")
  10. .getMany();
  11. }).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.