Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Relations

One-to-One Relations

Model one-to-one relations with TypeORM @OneToOne and @JoinColumn and Sequelize hasOne and belongsTo, choose the owning side, enforce uniqueness, and test it in a runnable stand-in.

A user has exactly one profile. An order has one invoice. A one-to-one relation is a many-to-one where the foreign key is also unique, so at most one row can point at each parent. Use it to split rarely-used or sensitive columns into a separate table, or to model a true "has one" link.

Library code is read-only; the stand-ins demonstrate the unique foreign key and the two ways of loading.

Which side owns the key?

Unlike one-to-many, either table could hold the foreign key, so you must choose. The table with the key is the owning side. A good rule: the key goes on the table that cannot exist without the other. A profile cannot exist without a user, so profiles.user_id is the key.

erDiagram
  USER ||--o| PROFILE : has
  USER {
    int id PK
    string email
  }
  PROFILE {
    int id PK
    int user_id FK "UNIQUE"
    string bio
  }

profiles.user_id is unique: each user has zero or one profile.

TypeORM

TypeScript
@Entity()
export class User {
  @PrimaryGeneratedColumn() id!: number;
  @Column() email!: string;

  @OneToOne(() => Profile, (profile) => profile.user)
  profile?: Profile;                         // inverse side: no column here
}

@Entity()
export class Profile {
  @PrimaryGeneratedColumn() id!: number;
  @Column({ type: "text", nullable: true }) bio!: string | null;

  @OneToOne(() => User, (user) => user.profile, { onDelete: "CASCADE" })
  @JoinColumn({ name: "user_id" })           // required on the owning side
  user!: User;
}

@JoinColumn() is mandatory on exactly one side of @OneToOne: that side owns the foreign key, and TypeORM adds a unique constraint for it.

TypeScript
const user = await users.save({ email: "[email protected]" });
await profiles.save({ bio: "Hello!", user });

const withProfile = await users.findOne({ where: { id: user.id }, relations: { profile: true } });
console.log(withProfile?.profile?.bio);

Sequelize

TypeScript
User.hasOne(Profile, { foreignKey: { name: "userId", allowNull: false, unique: true }, as: "profile", onDelete: "CASCADE" });
Profile.belongsTo(User, { foreignKey: "userId", as: "user" });

hasOne puts the key on the target (Profile.userId), belongsTo on the source. The two calls together describe one relation. Sequelize does not add unique on its own for hasOne, so write it in the foreign key options, as above, if you want the database to guarantee one profile per user.

TypeScript
const user = await User.create({ email: "[email protected]" });
await user.createProfile({ bio: "Hello!" });
const withProfile = await User.findByPk(user.id, { include: [{ model: Profile, as: "profile" }] });

The unique key does the real work

Without the UNIQUE constraint a one-to-one is only a convention, and a bug can insert two profiles for one user.

Node.js UNIQUE foreign key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Loading either direction

From the user you ask for profile; from the profile you ask for user. If you only need the owning side's key (the user id of a profile), you do not need to load the relation at all, which saves a JOIN: add a plain userId column property next to the relation (TypeORM) or read profile.userId (Sequelize, where the foreign key is an attribute).

Node.js Attach a one-to-one by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

When not to use one-to-one

  • If the columns are always read together and the table is small, keep them in one table. A split costs a JOIN.
  • If the second table could ever hold more than one row per parent, use one-to-many from the start.
  • Splitting large or rarely used columns (long bios, settings blobs) into a side table keeps the hot table narrow, which is a legitimate reason.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What makes a relation one-to-one rather than one-to-many?

    A unique foreign key allows at most one child row per parent.
  2. 2. Where must @JoinColumn be placed in a TypeORM @OneToOne relation?

    Exactly one side declares @JoinColumn and holds the key.
  3. 3. Which Sequelize call puts the foreign key on the target model?

    hasOne adds the key to the target; belongsTo adds it to the source.
  4. 4. A user without a profile is loaded with its profile relation. What is profile?

    A missing related row is null; your code should handle it.

Summary

  • One-to-one is a foreign key plus a unique constraint.
  • Put the key on the table that depends on the other, and mark that side as owning (@JoinColumn, belongsTo).
  • TypeORM: @OneToOne + @JoinColumn; Sequelize: hasOne + belongsTo.
  • The inverse side can be missing; code must handle null.
  • Use it for dependent or rarely read data, not as a default.

Next: Many-to-Many Relations