Creating and using linked schema models

Let’s say you have 2 schema models

model User {
    id           String    @id @default(uuid())
    email        String    @unique
    firstName    String
    lastName     String
    publications Project[]
}

model Project {
    id         String          @id @default(uuid())
    title      String          @unique
    author     User            @relation(fields: [authorId], references: [id])
    authorId   String
}

After you set up the DB, generated the SDL files properly and your ProjectsCell.tsx, you can customise the GraphQL query to return any field in the 2 linked models, like this:

export const QUERY = gql`
  query ProjectsQuery {
    projects {
      id
      title
      author {
        id
        firstName
        lastName
      }
    }
  `

But when you actually try to render the data, you might get complaints from TS.
image

The error is something like Property 'firstName' does not exist on type '{ __typename?: "User"; id: string; }'. ts(2339)

The solution is simple, just restart VS Code and the server using yarn rw dev, which will regenerate the types in web/types/gaphql.d.ts and the data should be correctly rendered.

I was stuck on this for hours until I got help in the Discord #quick-help channel from the community and the RedwoodJS core team, so I’m passing on the tip here :slight_smile: .

Happy coding!

4 Likes