---
url: /relationships.md
---

# Relationships

Related items in SignalDB live in separate collections and refer to each other by id, like foreign keys in a relational database. A query always targets a single collection. Instead of a join inside the query language, you combine queries in your code, and because every one of them is reactive, the combined result stays up to date when any of the related items changes.

The examples below use these collections:

```js
import { Collection, DefaultDataAdapter } from '@signaldb/core'

const dataAdapter = new DefaultDataAdapter()

const Users = new Collection('users', dataAdapter)       // { id, name, country }
const Posts = new Collection('posts', dataAdapter)       // { id, title, authorId, tagIds, createdAt }
const Comments = new Collection('comments', dataAdapter) // { id, postId, authorId, text }
const Tags = new Collection('tags', dataAdapter)         // { id, name }
```

## Modeling relationships

| Relationship | Stored as | Resolved with |
| --- | --- | --- |
| One-to-one / many-to-one | an id on the referencing item (`post.authorId`) | `Users.findOne(post.authorId)` |
| One-to-many | the id of the parent on every child (`comment.postId`) | `Comments.find({ postId: post.id })` |
| Many-to-many | an array of ids (`post.tagIds`) | `Tags.find({ id: { $in: post.tagIds } })` |

Index the fields you look up often, such as `postId` or `authorId`, with the collection's [`indices` option](/reference/core/collection/#constructor), so resolving a relationship doesn't scan the whole collection.

## Resolving relationships on an item

The most convenient way to follow a relationship is a method on the item. A collection's `transform` option turns every item into an instance of your class, so its methods are available wherever you read the item:

```js
class Post {
  constructor(data) {
    Object.assign(this, data)
  }

  getAuthor() {
    return Users.findOne(this.authorId)
  }

  getComments() {
    return Comments.find({ postId: this.id })
  }
}

const Posts = new Collection('posts', dataAdapter, { transform: item => new Post(item) })

effect(() => {
  const post = Posts.findOne({}, { sort: { createdAt: -1 } })
  console.log(post?.getAuthor()?.name, post?.getComments().count())
})
```

Each method runs a regular query, so inside a reactive scope the effect reruns when the post, its author or its comments change. The [ORM guide](/orm/) shows the pattern in depth, including chaining relationships across several collections and keeping it type-safe.

## Loading related data in bulk with `transformAll`

Calling `post.getAuthor()` for every post of a list runs one query per post, the N+1 problem. The `transformAll` option of a collection receives the whole result of a query instead, so it can load the related items with a single `$in` query and attach them to every item. See [Solving the N+1 Problem with transformAll](/orm/#solving-the-n-1-problem-with-transformall) for how it works, how it is read in reactive and asynchronous queries, and a complete example.

## Filtering and sorting by related data

Since a query targets one collection, a condition on a related collection takes two steps: query the related collection for the ids you need, then use them in the selector of the main query:

```js
effect(() => {
  // posts written by users from Germany
  const authorIds = Users.find({ country: 'DE' }, { fields: { id: 1 } })
    .fetch()
    .map(user => user.id)

  const posts = Posts.find(
    { authorId: { $in: authorIds } },
    { sort: { createdAt: -1 } },
  ).fetch()
})
```

Both queries are reactive: a user who moves to another country, or a new post by a German author, updates `posts` automatically.

To sort by a field of a related item, for example by author name, load the related items (with `transformAll` or a second query) and sort the combined list in your code. Keep such lists small with a `limit` or a narrow selector, because the sort happens outside the query.

## How this compares to joins

Databases with a join operator, like SQL or [TanStack DB](/comparison/#signaldb-vs-tanstack-db), let you express a relationship inside a single query, and the engine evaluates the join. SignalDB can express the same relationships, composed from single-collection queries in your code instead. You lose the single declarative statement, and conditions on related data take an extra step. In return, every piece stays a plain, indexable, reactive query that works the same with every [data adapter](/data-adapters/) and [storage adapter](/data-persistence/).
