Skip to content

Add the ability to set a foreign key on a model to create relationships #296

@canrozanes

Description

@canrozanes

It would be great if developers could be a given the option to create one-to-one relationships using foreign keys. This pattern should feel natural for developers who are familiar with relational databases.

import { factory, primaryKey, foreignKey } from '@mswjs/data'

const db = factory({
  user: {
    id: primaryKey(String),
    publications: manyOf('post'),
  },
  post: {
    id: primaryKey(String),
    userId: foreignKey("user")
    title: String,
  },
})

And then we could get posts belonging to a specific user with the following syntax.

const user = db.user.findFirst({
   where: {
      id: "abc"
   }
})

const userBlogPosts = db.post.findMany({
   where: {
      user_id: user.id
   }
})

Alternatively, the library could implicitly create a userId field on a blogPost if blogPost was declared with a oneOf("user") relationship. I think this is what mirage does.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions