Creating a Prisma schema with a complex nested structure and incorporating an array of strings for a specific property

I'm trying to create a detailed Prisma schema for a product database that includes nested properties and an array of strings for image content. The structure I'm aiming for looks like this:

 interface Product {
    id: number;
    name: string;
    description: string;
    price: number;
    rating: number;
    category: string;
    retailer: string;
    location: {
        name: string;
        coordinates: {
            longitude: number;
            latitude: number;
        };
    };
    images: {
        thumbnail: string;
        content: string[];
    };
    createdAt: Date;
    updatedAt: Date;
}
 

I am particularly struggling with how to model the images property in my Prisma schema, where content is an array of strings.

Here's what I've tried so far:

 generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlserver"
  url      = env("DATABASE_URL")
  relationMode = "prisma"
}

model Product {
  id          Int        @id @default(autoincrement())
  name        String
  description String
  price       Float
  rating      Float
  category    String
  retailer    String
  location    Location[]
  images      Images[]
  createdAt   DateTime   @default(now())
  updatedAt   DateTime   @updatedAt
}

model Images {
  id          Int        @id @default(autoincrement())
  thumbnail   String
  content     String
  productId   Int        @unique
  product     Product    @relation(fields: [productId], references: [id])
}

model Location {
  id          Int        @id @default(autoincrement())
  longitude   Float
  latitude    Float
  address     String
  productId   Int        @unique
  product Product        @relation(fields: [productId], references: [id])
}
 

However, this schema generates an error regarding lists of primitive types not being supported, and though it is close enough, it isn't quite right.

How can I accurately represent this intricate structure in my Prisma schema while ensuring compatibility with a SQL Server database? Any insights or recommendations would be highly appreciated. Thank you!

Answer №1

It's time to simplify things - let's explore further! By stripping away the basic data types, we uncover:

interface Product {
  location: {
    name: string;
    coordinates: {
      longitude: number;
      latitude: number;
    };
  };
  images: {
    thumbnail: string;
    content: string[];
  };
}

Your Prisma schema contains some errors:

model Product {
  id          Int        @id @default(autoincrement())
  location    Location[] // location should not be an array in the interface
  images      Images[]   // images should not be an array
}

model Location {
  id          Int        @id @default(autoincrement())
  longitude   Float
  latitude    Float
  address     String     // Where did this come from?
  productId   Int        @unique
  product Product        @relation(fields: [productId], references: [id])
}

If your interface is accurate, here's how to represent it in your schema - focusing on relevant parts:

model Product {
  id         Int      @id @default(autoincrement())
  /// Referring to exactly 1 location
  images     Images   @relation(fields: [imagesId], references: [id])
  imagesId   Int
  location   Location @relation(fields: [locationId], references: [id])
  locationId Int
}

model Location {
  id            Int         @id @default(autoincrement())
  name          String
  coordinates   Coordinates @relation(fields: [coordinatesId], references: [id])
  coordinatesId Int
  address       String
  productId     Int         @unique
  products      Product[]
}

/// A "helper model" to represent the coordinates of a location
model Coordinates {
  id        Int        @id @default(autoincrement())
  longitude Float
  latitude  Float
  locations Location[]
}

model Images {
  id        Int            @id @default(autoincrement())
  thumbnail String
  /// One to many relation with ImageContent
  contents  ImageContent[]
  /// Unfortunately, not supported by SQL Server, hence the solution above
  /// contents  String[]
  products  Product[]
}

model ImageContent {
  id       Int     @id @default(autoincrement())
  content  String
  images   Images? @relation(fields: [imagesId], references: [id])
  imagesId Int?
}

Since SQL Server does not support string arrays (source), a workaround using an ImageContent model is necessary for hosting the content array.

I have confirmed the validity of this schema with VS Code + Prisma extension and it appears to be correct. I highly recommend utilizing this extension for validation, formatting, and even automatic creation of certain relations within your schema.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for retrieving information from a Vuetify modal window

Is it possible to retrieve data from a dialog in the VueJS Vuetify framework? Specifically, how can I access the username or password entered in the NewUserPopup.vue dialog from app.vue? App.vue = main template NewUserPopup.vue = Dialog template imported ...

Ensuring Consistency in Array Lengths of Two Props in a Functional Component using TypeScript

Is there a way to ensure that two separate arrays passed as props to a functional component in React have the same length using TypeScript, triggering an error if they do not match? For instance, when utilizing this component within other components, it sh ...

What is the best way to solve the Hackerrank Binary Tree problem using TypeScript and output the

Here is the coding challenge from Hackerrank: Given a pointer to the root of a binary tree, you are required to display the level order traversal of the tree. In level-order traversal, nodes are visited level by level from left to right. Implement the fun ...

Top recommendation on how to effectively incorporate clerk into supabase

After developing my own custom react hook to manage supabase, I am unsure if it is a good idea to use this hook universally due to the persistent need to handle isLoading each time it is implemented. import { useEffect, useState } from 'react' im ...

Component in Next Js fails to pass props when using getInitialProps

I am facing some challenges with Next Js and could really use some assistance. We have a component where I am utilizing "getInitialProps" to pass props to it during the server-side rendering process. However, no matter what I try, the props do not seem to ...

Fly.io encountered an issue when attempting to retrieve an image or build from the source. The error occurred while rendering the push status stream and resulted in an unexpected HTTP status: 502 Bad

Recently, I tried deploying my Next.js app on fly.io but encountered issues. Strangely, I was able to deploy it before without any problems. Can anyone offer assistance with this current situation? Your help would be greatly appreciated. fly deploy ...

Encountering an "Unspecified Reference Error" while attempting to retrieve data from an API in your

I've been attempting to utilize a mock API from in order to fetch data for my Next.js application. However, I am consistently encountering an undefined reference error, despite following the code snippet provided in the official Next.js documentation ...

Trying to figure out how to efficiently store data in an object within a multi-step survey using setState

I have a questionnaire with 20 questions and I'm attempting to save the responses in an object using the useState hook. I've been struggling with it for a while now. Here's a link to my CodeSandbox: https://codesandbox.io/s/radio-group-cont ...

When onSubmit is triggered, FormData is accessible. But when trying to pass it to the server action, it sometimes ends up as null

I am currently utilizing NextJS version 14 along with Supabase. Within my codebase, I have a reusable component that I frequently utilize: import { useState } from 'react'; interface MyInputProps { label: string; name: string; value: stri ...

Make the text stand out by highlighting it within a div using a striking blue

Currently, I am working with Angular2 and have incorporated a div element to display multiple lines of text. Positioned below the text is a button that, when clicked, should select the entirety of the text within the div (similar to selecting text manually ...

Comparing ESLint and TSLint: Which One Is Right for You

After looking through numerous sources, I came up empty-handed regarding this particular question. Could anyone provide insight on the drawbacks of using Eslint compared to TsLint? What are the reasons for transitioning to ESLint? ...

Oops! There seems to be a hiccup: Unable to locate the control with the specified path: 'emails -> 0 -> email'

I am attempting to design a form incorporating a structure like this: formGroup formControl formControl formArray formGroup formControl formControl However, upon clicking the button to add reactive fields and submitting the form ...

Tips for validating email addresses and enforcing minimum length requirements

In order to validate email input for the correct format and ensure minimum length validations for first name and password, I am looking to utilize only bootstrap. While I have successfully implemented required field validations for the inputs, I am unsure ...

Need at least one of two methods, or both, in an abstract class

Consider the following scenario: export abstract class AbstractButton { // Must always provide this method abstract someRequiredMethod(): void; // The successor must implement one of these (or both) abstract setInnerText?(): void; abst ...

Is it possible for Typescript to allow extracted interfaces while excluding properties from another interface?

I've been searching for information on the specific features of this. Despite my efforts on Google, I have been unable to find the details. Any help would be greatly appreciated! interface Numbers { number: number; number2: number; number ...

Tips for sending properties to a child component in a React Native project using TypeScript

Here is the setup in my parent component: const [OTPNotify, setOTPNotify] = useState("flex"); const closeOTPNotify = () => { setOTPNotify("none"); } <OTPRibbonComponent onCancel={closeOTPNotify} display={OTPNotify}/> Now, ...

What steps should I take to address conflicting type identifiers between Cypress and jQuery?

Currently, I am tasked with writing TypeScript end-to-end tests for an Angular 11 application. Following the recommended practices of Cypress, my test setup is encountering a conflict due to existing jQuery dependencies (3.5.1) in the app and Cypress (8.4. ...

Explore Angular's ability to transform a nested observable object into a different object

My task involves mapping a field from a sub object in the response JSON to the parent object The response I receive looks like this: { "id": 1, "name": "file-1", "survey": { "identifier": 1, "displayedValue": survey-1 } } I am attempting ...

Safari is not allowing the cookie to be set

Currently, my Next.js backend is set up as a proxy to forward requests to another backend. Upon receiving a response, it then proceeds to establish a secure HTTP only cookie. Below is the relevant code snippet: const handler = (req: NextApiRequest, res: Ne ...

Utilize Array.push to add 2 new rows to a table using Angular 4

I have two arrays that are almost identical, except for two items which are the fakeDates: this.prodotti.push({ idAgreement: this.idAgreement,landingStatus: this.landingStatus, landingType: this.landingType, startDate: this.startDate, expirationDate: thi ...