https://www.prisma.io/ logo
Join SlackCommunities
Powered by
# orm-help
  • b

    bob

    01/17/2022, 1:04 AM
    alright upon further poking around. it appears that two of my relations are returning undefined.
  • b

    bob

    01/17/2022, 1:12 AM
    i wrote a script and checked every row + relation. every relation/ID exists in my entire set. when I loop through each row, there are zero nulls
  • b

    bob

    01/17/2022, 1:13 AM
    it appears that when I request to many rows it starts to fail
  • b

    bob

    01/17/2022, 1:18 AM
    hmm I found the issue. one of the IDs don't exist. 🤦 alright. how can I enforce relations, check that the IDs exist. I enabled referential Integrity
    Copy code
    generator client {
      provider        = "prisma-client-js"
      previewFeatures = ["dataProxy", "referentialIntegrity"]
    }
    
    datasource db {
      provider             = "mysql"
      url                  = env("DATABASE_URL")
      referentialIntegrity = "prisma"
    }
  • k

    kailoon

    01/17/2022, 4:45 AM
    Hi there, I am total newbie in data model. Can I have your advice here? I am trying to build an online order app using nextjs and planetscale. Basically, user can create digital menu and share it so customer can order via whatsapp. Attached is the schema I have. Features: 1. user has many restaurants ( menu ) 2. menu has many sections 3. menu has many items 4. item has many options / variants 5. user has many orders 6. order has many order items for variants and options, user can create it and assign to any items. Or maybe just assign to a section, I am not sure which works better...
    Copy code
    generator client {
      provider        = "prisma-client-js"
      previewFeatures = ["referentialIntegrity"]
    }
    
    datasource db {
      provider             = "mysql"
      url                  = env("DATABASE_URL")
      referentialIntegrity = "prisma"
    }
    
    // user has many restaurants
    model User {
      id          String       @id @unique @default(cuid())
      name        String
      restaurants Restaurant[]
      orders      Order[]
    }
    
    // restaurant has many sections, items
    
    model Restaurant {
      id     String @id @unique @default(cuid())
      name   String
      userId String
    
      User              User               @relation(fields: [userId], references: [id])
      sections          Section[]
      items             Item[]
      itemOptions       ItemOption[]
      itemOptionValues  ItemOptionValue[]
      itemVariants      ItemVariant[]
      itemVariantValues ItemVariantValue[]
      orders            Order[]
      address           Address?
    
    }
    
    model Section {
      id           String  @id @unique @default(cuid())
      name         String
      restaurantId String?
    
      Restaurant Restaurant? @relation(fields: [restaurantId], references: [id])
      items      Item[]
    }
    
    model Item {
      id           String  @id @unique @default(cuid())
      name         String
      price        Decimal
      restaurantId String?
      sectionId    String?
    
      Restaurant   Restaurant?   @relation(fields: [restaurantId], references: [id])
      Section      Section?      @relation(fields: [sectionId], references: [id])
      itemOptions  ItemOption[]
      itemVariants ItemVariant[]
    }
    
    // multiple choices eg: extra cheese, extra sauce etc.
    model ItemOption {
      id           String  @id @unique @default(cuid())
      name         String
      restaurantId String?
      itemId       String?
    
      Restaurant Restaurant? @relation(fields: [restaurantId], references: [id])
      Item       Item?       @relation(fields: [itemId], references: [id])
    }
    
    model ItemOptionValue {
      id           String  @id @unique @default(cuid())
      name         String
      price        Decimal
      restaurantId String?
    
      Restaurant Restaurant? @relation(fields: [restaurantId], references: [id])
    }
    
    // sizes, flavor and toppings etc
    model ItemVariant {
      id           String  @id @unique @default(cuid())
      name         String
      restaurantId String?
      itemId       String?
    
      Restaurant Restaurant? @relation(fields: [restaurantId], references: [id])
      Item       Item?       @relation(fields: [itemId], references: [id])
    }
    
    model ItemVariantValue {
      id           String  @id @unique @default(cuid())
      name         String
      price        Decimal
      restaurantId String?
    
      Restaurant Restaurant? @relation(fields: [restaurantId], references: [id])
    }
    
    model Order {
      id           String  @id @unique @default(cuid())
      name         String
      total        Decimal
      userId       String?
      restaurantId String?
    
      orderItems OrderItem[]
      User       User?       @relation(fields: [userId], references: [id])
      Restaurant Restaurant? @relation(fields: [restaurantId], references: [id])
    }
    
    model OrderItem {
      id       String  @id @unique @default(cuid())
      name     String
      quantity Int
      price    Decimal
      orderId  String?
    
      Order Order? @relation(fields: [orderId], references: [id])
    }
    
    model Address {
      id           String  @id @unique @default(cuid())
      name         String
      latitudes    Decimal @db.Decimal(8, 6)
      longitudes   Decimal @db.Decimal(9, 6)
      restaurantId String  @unique
    
      Restaurant Restaurant @relation(fields: [restaurantId], references: [id])
    }
    Am I doing it correctly? I wanted to be able to list the orders, number of an item being ordered for the owner as a stats/report. Also, an order summary for the customer to refer to as a receipt. Thanks for your help!
  • k

    koenie-06

    01/17/2022, 8:26 AM
    Hello everyone, can anyone explain how i get the properties of the object that you get back from the json type of prisma? It says that the value .name not exists. I'm in typescript
    m
    • 2
    • 8
  • r

    Reuben Porter

    01/17/2022, 9:28 AM
    Hi all, I'm working on a feature where it's possible many resources can be created in a single endpoint. I've tried using
    createMany
    as the
    skipDuplicates
    flag is a useful feature for me, plus
    createMany
    is more performant than a loop with multiple single
    create
    . My issue is that
    createMany
    does not return the created values, and I need those values to perform another action - e.g. a notification email. I have found this thread, but nothing in there really helps my case https://github.com/prisma/prisma/issues/8131. I thought about using a loop and storing the promises in an array, then waiting for them all to be settled etc, however I haven't been able to get this to work and Prisma/TS isn't happy. Any suggestions greatly appreciated!
    m
    • 2
    • 2
  • d

    Deepak Guptha S

    01/17/2022, 10:48 AM
    👋 Hello Everyone, This is my first post, I need to perform Prisma query example:
    Copy code
    SELECT * FROM employee_profile WHERE month(date_of_birth) = 12 AND year(date_of_birth) = 1990
    I searched for the Prisma docs, but I couldn't find the equivalent Prisma functions to use the SQL functions like
    month()
    ,
    year()
    Is there any solution ?
    m
    • 2
    • 2
  • c

    Claudiu Constantin Cojocaru

    01/17/2022, 12:05 PM
    Hello everyone
    👋 1
  • b

    bob

    01/17/2022, 12:32 PM
    does anyone have experience with prisma and cloudflare? I run into an error where it states that I have used over 50 subrequests from cloudflare. i wonder if its related to the proxy...
  • k

    koenie-06

    01/17/2022, 1:07 PM
    Is there a possible way to extend the 'JsonArray' class? It gives me a error whenever i try to extend it
    • 1
    • 1
  • m

    Mischa

    01/17/2022, 1:30 PM
    Any way to query
    created < NOW() - INTERVAL '1 day'
    ?
    r
    m
    • 3
    • 11
  • e

    Eudes TenĂłrio

    01/17/2022, 4:04 PM
    Hey guys! Is there no way to change the type/interface of a Json field?
  • k

    koenie-06

    01/17/2022, 7:18 PM
    Is there a way to insert the Date.now() into a mysql DB?
  • k

    koenie-06

    01/17/2022, 7:19 PM
    As like, what datatype should it be
  • n

    Nathaniel Babalola

    01/17/2022, 7:21 PM
    Hi all , please how do I go about this. When a field is
    Copy code
    DateTime @db.Time()
    Should I pass in a JavaScript date object or just a time string. Will the db.Time() format it for me if I were to pass in a date object?
  • b

    Bailey McKay

    01/18/2022, 3:10 AM
    Hi all, I’m a long time (2+ years) user of Prisma1, but I’m new to the slack. I just upgraded to Prisma2 this weekend (it wasn’t as painful as I thought it would be). I’m liking the new features (e.g. transactions) and syntax. However, one of the things I’m really missing is the auto-generated “WhereInputs” that Prisma1 gave you. It was very handy to be able to create a little query with custom where filtering specific to that query (often a one-off on the frontend) and not have to write a new backend service. I understand not wanting to expose the entire CRUD, but having the ability to generate all the WhereInputs for my schema for querying on the frontend would be helpful (I really don’t want to do it by hand). Does this exist? Has anyone else had this need? Thanks, Bailey
    s
    m
    • 3
    • 5
  • j

    Jakub Figlak

    01/18/2022, 7:54 AM
    Hi folks! I am building a backend for football/soccer scouting app. Among many others, I need
    clubs
    ,
    competitions (leagues)
    and
    seasons
    tables in my database. I'm also using a table called
    competition_participations
    to keep track of in which league was the club participating during particular season. I'm kinda struggling with modeling competitions (leagues) data. My problem is that there are leagues that are divided into groups and the club is participating in that particular group, but there are also top-level leagues that are not divided into any groups. Let's talk about Bundesliga here, as Prisma's headquarters is in Berlin 😄 Here is an example: 1. Bayern participates in
    Bundesliga
    , no groups 2. Heidenheim participates in
    2. Bundesliga
    , no groups 3. FC Kaiserslautern participates in
    3. Liga
    , no groups 4. VfB Oldenburg participates in
    Regionalliga North
    - top level competition is
    Regionalliga
    , group is
    North
    5. Alemannia Aachen participates in
    Regionalliga West
    - top level competition is
    Regionalliga
    , group is
    West
    How would you model that? I was thinking of something like
    Copy code
    model Division {
      id          String   @id @default(cuid())
      name        String
      level.      Int // 1, 2, 3, etc..
      isJunior    Boolean @default(false)
      isWomen     Boolean @default(false)
      createdAt   DateTime @default(now())
      updatedAt   DateTime @updatedAt
    
      // Relation fields
      country   Country                    @relation(fields: [countryId], references: [id])
      countryId String
      league League[]
    }
    
    model League {
      id            String      @id @default(cuid())
      name          String
    
      // Relation fields
      division   Division @relation(fields: [divisionId], references: [id])
      divisionId String
    }
    But it seems a little bit dirty to have to create
    Bundesliga
    as a division and as a league. Do you have any recommendations?
    s
    • 2
    • 6
  • r

    Reuben Porter

    01/18/2022, 8:35 AM
    Hello, Currently struggling to create what is probably a pretty straight forward query, but here's my question: Currently, I have 2 tables, 
    publication
     and 
    publicationStatus
    . A publication will looking something like:
    Copy code
    {
      "id": "ckyil950d00027v2str5ljo7h",
      "url_slug": "ckyil950e00037v2s4mqxvaho",
      "type": "PEER_REVIEW",
      "title": "Intersting review",
      "content": "Content is optional at this stage",
      "doi": "1093/ajae/aaq063",
      "createdBy": "test-user-1",
      "createdAt": "2022-01-17T11:12:50.845Z",
      "updatedAt": "2022-01-17T11:12:50.847Z",
      "publicationStatus": [
        {
          "status": "LIVE",
          "createdAt": "2022-01-19T11:12:50.846Z",
          "id": "ckyil950e00047v2sx4urbfte"
        },
        {
          "status": "DRAFT",
          "createdAt": "2022-01-17T11:12:50.846Z",
          "id": "ckyil950e00047v2sx4urbfth"
        }
      ],
      "user": {
        "id": "test-user-1",
        "firstName": "Test",
        "lastName": "User 1"
      }
    }
    Where 
    publication
     has a 1 to many relationship with 
    publicationStatus
    . What I need to do is a 
    find
     query where it only returns a 
    publication
     if the latest 
    publicationStatus
     for that 
    publication
    , has a 
    status
     of 
    LIVE
    . The closest I could come to is this psuedo code (does not work, but demonstrates a picture of what I am trying to do):
    Copy code
    await prisma.publication.findFirst({
        where: {
            id,
            publicationStatus: {
                where: {
                    status: 'LIVE'
                },
                take: 1,
                orderBy: {
                    createdAt: 'desc'
                }
            },
        }
    });
    👀 1
  • j

    Jonas

    01/18/2022, 9:49 AM
    What is the easiest way to check if a PrismaClient instance is closed/disconnected?
    s
    n
    • 3
    • 7
  • j

    Jonas

    01/18/2022, 10:39 AM
    Any prisma maintainers maybe having knowlegde of any secret attributes for this or something? 😄
  • n

    Nathaniel Babalola

    01/18/2022, 11:23 AM
    Hi all , please can someone help with this . I am getting a
    Copy code
    PrismaClientKnownRequestError: 
    Invalid prisma.restaurant.create() invocation:
    Copy code
    Failed to validate the query: Unable to match input value to any allowed input type for the field. Parse errors: [Query parsing/validation error at
    Yet my data is being created in the database and it still returns this error. Any help is greatly appreciated.
    • 1
    • 1
  • j

    Jonas

    01/18/2022, 1:35 PM
    Is there a way to automatically generate a Graql Schema from the Prisma Schema?
    n
    b
    • 3
    • 2
  • h

    Henri Kuper

    01/18/2022, 1:58 PM
    Hi all, I am really having trouble using prisma studio with a larger data base, because prisma studio handles n:m relations in a way that makes it incredible slow. Some of these relations have over 10000 connections. I guess Prisma studio uses the include option for all attributes. This leads to more than 10,000 connections being requested and sent. Since this leads to very large amount of data, it results in a timeout/freeze. For example, you have a model
    user
    with the attribute
    follower
    . A user has 10k followers. Prisma studio would then request the data of all 10k followers as soon as this specific user is requested. Even if you unselect certain attributes in Prisma studio, they are still requested. 1. does anyone else has this kind of trouble and already found a solution/workaround? 2. why does prisma studio use include to show the number of relations instead of _count? This would probably speed up the whole process by a lot, I guess.
  • k

    Kasir Barati

    01/18/2022, 2:04 PM
    Hi I am using Docker Compose to run my database engine. And now I face this Error. What is it?
    Copy code
    $ npx prisma migrate dev
    Environment variables loaded from .env
    Prisma schema loaded from prisma/schema.prisma
    Datasource "db": PostgreSQL database "nest_base", schema "public" at "localhost:5432"
    
    Already in sync, no schema change or pending migration was found.
    
    Error: ENOENT: no such file or directory, copyfile '/path/to/node_modules/@prisma/index.d.ts' -> '/path/to/node_modules/@prisma/client/index.d.ts'
  • r

    Rafael Carneiro

    01/18/2022, 2:12 PM
    Hey, I try to get all assets/items and count their downloads just of the last 7 days. Counting all downloads, or getting the full download model back (without count aggregate, which I dont want) works. Is it just not possible yet, to filter aggregates? I really don't know how to make this work. Any help would be much appreciated!
  • r

    Rafael Carneiro

    01/18/2022, 2:13 PM
    What I basically need:
  • k

    koenie-06

    01/18/2022, 4:31 PM
    Whenever i try to use the .delete() function it gives me a error.. My code is
    Copy code
    await prisma.tickets.delete({
            where: {
                channelId: interaction.channelId,
                guildId: interaction.guildId
            }
        });
    And my error is
    Copy code
    Type '{ channelId: any; guildId: any; }' is not assignable to type 'ticketsWhereUniqueInput'.
      Object literal may only specify known properties, and 'channelId' does not exist in type 'ticketsWhereUniqueInput'.
  • h

    Harry Cheslaw

    01/18/2022, 5:05 PM
    hey everyone! 👋 My backend is receiving an array of objects to update in the database. At the moment, to achieve this I am having to loop through the objects and create unique requests and I am then executing all these individual prisma queries within a transaction. Is there a better way of doing it? When i look at the generated SQL there are a large number of queries performed individually vs in aggregate
  • b

    Benny Kachanovsky

    01/18/2022, 6:02 PM
    Hi, is there a way to reference an existing table that *is not in Prisma'*s schema? for example i have existing User table. Im creating a Post model in Prisma that i want to have a foreign key to User. If there is not built-in way, the best option is to change the generated migration files that responsible on the addition of Post model?
1...533534535...637Latest