TypeORM By Example: Part 5
Exploring one-to-one relationships.

This article is part of a series starting with TypeORM By Example: Part 1.
The final example for this article is available for download.
Having spent so much time on other TypeORM topics, we finally get to the obvious topic of relationships; one-to-one, one-to-many, and many-to-many.
One-to-One Relationship — Defining
Let us implement a TodoMetadata entity to hold a single comment about a Todo.
src / entity / TodoMetadata
and update Todo to hold a reference to a TodoMetadata.
src / entity / Todo.ts
We build the application and generate a migration:
npm run build-ts
./node_modules/.bin/typeorm migration:generate -n TodoMetadata
the migration:
src / migration / 1535970439120-TodoMetadata.ts
We build the application and run the migration:
npm run build-ts
npm run start
The migration runs and we see our new todo_metadata table.

One-to-One Relationship — Creating
Let us now update the application to create the TodoMetadata alongside the Todo.
src / todoManager.ts
Observations:
- We rename the Todo repository and create a basic one for TodoMetadata
- We create a TodoMetadata and assign it to a Todo
- We need to save the TodoMetadata first; so that its id is assigned. After it is saved, we can save the Todo.
Looking at the log, we can see the updated code in action; first saving the TodoMetadata and the the Todo.

One-to-One Relationship — Reading
We update the TodoRepository with the relations in both the find and QueryBuilder syntax:
src / TodoRepository.ts
note: On a first pass at this, I named the Todo field todoMetadata instead of metadata. Ran into all sorts of trouble trying to get the QueryBuilder to work with this camel-case name.
Now with this in place, our queries return the todos with the metadata.


Next Steps
In the next article, TypeORM By Example: Part 6 we continue our exploration of one-to-many relationships.
✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.