Schema and Datatypes

Relations

OptimaDB supports two fundamental types of relations between tables: One and Many. These relations allow you to model real-world connections between your data in a simple and intuitive way.

Relation Types

  • One: Each record in the source table is related to a single record in the target table. (e.g., each post belongs to one user)
  • Many: Each record in the source table can be related to multiple records in the target table. (e.g., a user can have many posts)

Defining Relations: Example

Let's say you have two tables: Users and Posts. Each post is written by a single user, but a user can write multiple posts. To represent this, you simply reference the user from the posts table. OptimaDB will automatically handle the relationship for you.

typescript

typescript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

In this example:
  • Each Post has a UserID that references a single User (One relation).
  • Each User can be referenced by multiple Posts (Many relation from the user's perspective).

In practice, you define a relation by pointing a field (like UserID) to another table's primary key. OptimaDB will understand and manage the relationship for you.

Using Extend to Join Related Data

The Extend property can be used with Get or GetOne queries to automatically join related data. The returned record will include a key $[TableName] containing either a single record (for One relations) or an array of records (for Many relations).

typescript

typescript

1

2

3

4

5

6

This approach lets you easily retrieve related data—no need to write manual join logic.
Even better, the Extend argument is type-safe and checked at compile time, so you can't accidentally use an invalid table name or reference a table that isn't related. This helps prevent common mistakes and makes your code more robust.