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

    Orcioly Andrade Alves

    03/10/2022, 12:39 PM
    Bom dia galera, tudo bem? É o seguinte sempre trabalhei com ORM no backend NodeJS, antigamente eu utilizava o Sequelize e depois comecei a usar o TypeORM, mas de uns dias para cá comecei a estudar o PRISMA, até tenho gostado dele, mas estou com a seguinte dúvida. Como faço para reverter a última Migrate com ele, no Sequelize e TypeORM isso funciona sem probleas, mas no Prisma não consegui, até encontrei alguns comandos para zerar o banco, mas eu queria apenas a última migrate. Encontrei o seguinte comando em minhas pesquinas prisma migrate down --experimental no meu caso eu coloco: yarn prisma migrate down --experimental, mas não funciona. A versão que estou usando é a 3.10 Humildimente pergunto se alguém trabalha com ele e poderia me orientar? Abraço a todos...
    s
    • 2
    • 3
  • j

    Julien Demarque

    03/10/2022, 3:12 PM
    Hello! Is there a way to filter a subselection? Like if you have
    Copy code
    prisma.authors.findMany({
       where: {
           books: {
              id: {
                  IN: [1,2,3]
              }
         }
       }
    })
    This would filter the authors, but what i want is to get all the authors, but filter their book selection. How would I do that?
    n
    • 2
    • 3
  • a

    Anthony Roux

    03/10/2022, 4:35 PM
    Hello everyone! I discover Prisma as a student. And I'm having some difficulties. I can't get it to work so that when I submit a user with an email address already in the DB, it returns something other than a "unique field violation" error. Please, if someone could help me 😞 thanks
    j
    • 2
    • 35
  • s

    Shiva Kar

    03/10/2022, 5:35 PM
    👋 Hello, team!
    👋 1
  • s

    Shiva Kar

    03/10/2022, 5:43 PM
    can we do GridFs using prisma
    j
    • 2
    • 2
  • s

    Shiva Kar

    03/10/2022, 5:44 PM
    Mongo db storage
  • n

    Nathaniel Babalola

    03/10/2022, 7:53 PM
    Prisma timing out on Heroku Postgre is so frequent I'm tired. This just failed on my bitbucket-pipeline as it was deploying to Heroku. I will have to remove the postinstall script from my package.json.that runs "npx prisma migrate deploy" , because I don't want my deploys to fail. Then I will have to resort to running "migrate deploy" locally, copy all DATABASE_URL of all my environments being deployed to, add them to my .env file . And manually run "migrate deploy" for all of them. Is there any reason these things happen frequently ?
    v
    n
    j
    • 4
    • 5
  • m

    MacRae Linton

    03/10/2022, 10:27 PM
    Anyone ever gotten a Postgres Bytes field to work with $executeRaw()? Something is trying to base64 encode whatever is passed in in a way that is making it impossible for me to actually store the bytes I want in the database. Buffers work correctly in generated executors, but I am trying to use executeRaw to combine some operations that need to be in a transaction.
    j
    • 2
    • 5
  • j

    Juan Carlos Blanco Delgado

    03/10/2022, 11:43 PM
    Hi everyone, Anyone have any idea how to handle the best way revisions of a content in prisma with PostgreSQL?
    i
    • 2
    • 6
  • w

    William GM

    03/11/2022, 2:06 AM
    Hello Any plans on supporting
    tstzrange
    type?
    n
    • 2
    • 1
  • s

    SKhan

    03/11/2022, 6:44 AM
    Hi, I have 2 questions: 1 - Is following a good way to structure logic? LOGIC => A table for teams. There can only be 2 users in a team.
    Copy code
    model User {
      id              String               @id @default(cuid())
      team            Team[]
      ...
    }
    Copy code
    model Team {
      id          String        @id @default(cuid())
      member      User[]
      ...
    }
    QUESTION: Is this logic good or would it better to have two fields (member1 & member2) within the
    Team
    table, which would reference
    User
    ? 2 - The above logic is incorporated within Prisma. How do I query
    Team
    to get
    User
    . I get stuck because there are no foreign keys within Team referencing User.id, nor is there another table connecting Team -> User. (correction:) - There is a table
    _TeamToUser
    which only has 2 fields (A, B). (correction:) - Got this working with the following query.
    select * from "Team" inner join "_TeamToUser" on "Team".id = "_TeamToUser"."A" inner join "User" on "_TeamToUser"."B" = "User".id;
    Would love feedback to 1st question.
    n
    m
    • 3
    • 4
  • e

    Elliot Pitts

    03/11/2022, 8:45 AM
    I have an old Prisma 1 Cloud project that I need some help with. I will be later this year moving it over to Prisma 2, but my client is needing an audit of the current system. What I need is some info about Prisma 1 Cloud’s architecture but am struggling to find the relevant documentation. I need some clarity on how the db hosting is done (responsibilities, hardening, up-to-date software, encryption of the data). Can anyone point me in the right direction?
    n
    v
    a
    • 4
    • 6
  • m

    Michael Roberts

    03/11/2022, 12:12 PM
    Hi there, I'm thinking about utilising prisma in an up coming project. Could someone sell me the virtues of using Prisma over say, Firebase, as an ORM of choice.
    n
    • 2
    • 3
  • m

    Michael Roberts

    03/11/2022, 12:13 PM
    The stack is Go and Typescript, so it has come well recommended 🙂
  • m

    Michael Azogu

    03/11/2022, 12:52 PM
    how was Prisma made. I've been looking at the codebase & Wondering where you get the knowledge to be able to build such a beast
    prisma cool 2
    prisma green 2
    prisma rainbow 2
  • d

    Damien Duhamel

    03/11/2022, 3:43 PM
    Hi guys ! I have few random errors:
    P1001 Can't reach database server at xxxx:xxx
    So the Prisma client seems to lose the connection with the Postgresql DB obviously ... It’s not linked to the server load or too many connections because I have the same issue in staging environment (low trafic) It’s happening on two different services: a NodeJS API and a web worker Everything looks fine on Postgresql DB side and I have another very similar service connected to the same Postgresql DB but with Sequelize as ORM and no issue in this service Do you have any idea, what should I look for in order to fix it ?
    a
    • 2
    • 3
  • m

    Mischa

    03/11/2022, 4:08 PM
    Any idea why prisma might be spending so much time in
    readdirSync
    ?
    m
    a
    • 3
    • 2
  • p

    Paulo Menezes

    03/11/2022, 8:41 PM
    Hi, how can I filter all my customers who have a birthday today?
    Copy code
    const customers = await prisma.customer.findMany({
       where: {
         birthday: {
           equals: 'YYYY-03-11',
         },
       },
    });
    r
    • 2
    • 47
  • d

    Demian N

    03/11/2022, 9:45 PM
    Hi, I'm very new to prisma so please forgive me if the question sounds basic. How can I get the types of some particular Model to work under typescript. I'm not inferring them from a prisma query or mutation but I need to use them to work with something else. I came up that Prisma.<model>Select seems to give me the types of the Model I need. Am I correct?
    n
    • 2
    • 1
  • w

    William GM

    03/12/2022, 6:05 AM
    Hello. Having some trouble inserting a record using
    executeRaw
    , whenever I try to execute this code snippet I get the following error
    db error: ERROR: invalid input syntax for type timestamp with time zone: "$1"
    Copy code
    const { from, to } = createAppointmentDto;
    await prisma.$executeRaw`insert into public."Appointment" ("date", "patientId", "itemId") values ('[${from}, ${to})', ${id}, ${itemId});`;
    The weird part is that if I hardcode the dates directly as strings, IT WORKS!
    Copy code
    await prisma.$executeRaw`insert into public."Appointment" ("date", "patientId", "itemId") values ('[2010-01-01 14:45, 2010-01-01 15:45)', ${id}, ${itemId});`;
    Surely I'm missing something but don't know what it is. Thoughts?
    n
    • 2
    • 13
  • u

    user

    03/12/2022, 9:00 AM
    Prisma Meetup - Chance Strickland - Update While You Wait: Optimistic UI with Remix and Prisma

    https://www.youtube.com/watch?v=HEwWjCB9qIs▾

    ◭ Building UIs with instant user feedback when interacting with remote data has always been a challenge. We’ll show how Remix provides powerful APIs that make it easier than ever to perform optimistic updates, while Prisma beautifully simplifies the interface for updating your data. ◭ Chance is a software engineer at Remix who loves traveling, surfing, and helping developers like you build better websites and apps. ◭ Get in touch with Chance: https://twitter.com/chancethedev ◭ Join our Prisma Meetup group: https://www.meetup.com/pro/prisma-meetup/
  • o

    Octal pixel

    03/12/2022, 8:26 PM
    Is it possible to filter on include with a parent value to the include? Assuming I want to take the post that were created by user , 2 days after signing up . In the includes I need to write a condition for the created_at of post to be gte to the user's created_at
    n
    • 2
    • 1
  • j

    Jakub Figlak

    03/13/2022, 12:26 PM
    Hello good people! I'm building a football scouting app, actually rewriting it to nestjs & prisma. I have a following set of tables (among many others) - PLAYERS, TEAMS and TEAM_AFFILIATIONS:
    Copy code
    model TeamAffiliation {
      id        String    @id @default(cuid())
      startDate DateTime
      endDate   DateTime?
      createdAt DateTime  @default(now())
      updatedAt DateTime  @updatedAt
    
      // Relation fields
      player   Player @relation(fields: [playerId], references: [id])
      playerId String
      team     Team   @relation(fields: [teamId], references: [id])
      teamId   String
    }
    This table's responsibility is to keep the information to which team has the player been assigned within a certain time period (between
    startDate
    and
    endDate
    ). I also have a NOTES table, its simplified model looks like this:
    Copy code
    model Note {
      id               String   @id @default(cuid())
      docNumber        Int      @default(autoincrement())
      description      String?
      createdAt        DateTime @default(now())
      updatedAt        DateTime @updatedAt
    
      // Relation fields
      player           Player?         @relation(fields: [playerId], references: [id])
      playerId         String?
    }
    And here comes my question. On a note itself (when I'm for example fetching a list of notes) I need information to which team has the player been assigned when the note was created (it'd be perfect if I could filter notes by this piece of data). How would you approach this kind of problem? The simplest way would be just to create a field like
    playerCurrentTeam
    on a note and save it when a note is created. But it seems like a workaround, is there a better solution?
    n
    • 2
    • 2
  • a

    aj

    03/13/2022, 3:00 PM
    Hi! Kindly asking someones help. I need to insert a
    work
    record which has link to
    order
    ,
    user
    and
    location
    . Schema is as follows:
    Copy code
    model User {
      id            String          @id @default(cuid())
      email         String?         @unique
      orders        Order[]
    }
    
    model Order {
      id                 String          @id @default(cuid())
      orderNumber        Int
      user               User            @relation(fields: [userId], references: [id])
      userId             String
      origin             Location        @relation("OrderOrigin", fields: [orderOriginId], references: [id])
      orderOriginId      String
      destination        Location?       @relation("OrderDestination", fields: [orderDestinationId], references: [id])
      orderDestinationId String?
      work               Work?           @relation("OrderWork")
      includeLocations   Location[]      @relation("OrderIncludeLocations")
      excludeLocations   Location[]      @relation("OrderExcludeLocations")
    }
    
    model Work {
      id                    String     @id @default(cuid())
      origin                Location   @relation("WorkOrigin", fields: [workOriginId], references: [id])
      destination           Location   @relation("WorkDestination", fields: [workDestinationId], references: [id])
      stops                 Location[] @relation("WorkStops")
      originLocationId      String
      destinationLocationId String
      workOriginId          String
      workDestinationId     String
      workStopsId           String?
      order                 Order      @relation("OrderWork", fields: [orderId], references: [id])
      orderId               String     @unique
      status                WorkStatus @default(value: BOOKED)
    }
    
    model Location {
      id                    String  @id @default(cuid())
      address               String
      city                  String
      state                 String
      locationCode          String?
      workStops             Work[]  @relation("WorkStops")
      workOrigin            Work[]  @relation("WorkOrigin")
      workDestination       Work[]  @relation("WorkDestination")
      orderOrigin           Order[] @relation("OrderOrigin")
      orderDestination      Order[] @relation("OrderDestination")
      orderIncludeLocations Order[] @relation("OrderIncludeLocations")
      orderExcludeLocations Order[] @relation("OrderExcludeLocations")
    }
    Now when
    work
    is created
    order
    status becomes
    BOOKED
    . I can’t figure out how to upsert locations.
    Copy code
    let work = await prisma.work.create({
        data: {
            destination: {
                connectOrCreate: {
                    where: {
                        // address: data.work.destination.Address,
                        // city: data.work.destination.City,
                        state: data.work.destination.State,
                    },
                    create: {
                        address: data.work.destination.Address,
                        city: data.work.destination.City,
                        state: data.work.destination.State,
                    },
                },
            },
            origin: {
                connectOrCreate: {
                    where: {
                        // address: data.work.origin.Address,
                        // city: data.work.origin.City,
                        state: data.work.origin.State
                    },
                    create: {
                        address: data.work.origin.Address,
                        city: data.work.origin.City,
                        state: data.work.origin.State
                    },
                },
            },
            // stops: data.work.stops.map(stop => {
            //     return {
            //         connectOrCreate: {
            //             address: stop.Address,
            //             city: stop.City,
            //             state: stop.State,
            //         },
            stopsCount: 0,
            workOriginId: data.work.workOriginId,
            originLocationId: data.work.originLocationId,
            workDestinationId: data.work.workDestinationId,
            destinationLocationId: data.work.destinationLocationId,
            workStopsId:"1234",
            status: data.work.status,
            orderId: orderId,
        }
    a
    • 2
    • 1
  • i

    Isaac McFadyen

    03/13/2022, 8:24 PM
    Hey everyone! Just popped in to ask about the status of Prisma's Data Proxy. Currently it requires aliasing using
    esbuild
    or similar when used with Cloudflare Workers (otherwise it gives a "not allowed in browser" error). What's the blocker on removing this bundle requirement?
    v
    • 2
    • 1
  • m

    Matias Filliez

    03/14/2022, 4:13 AM
    Hola a todos espero que esten muy bien, por casualidad alguien deployo prisma en heroku?
    v
    • 2
    • 1
  • d

    Dev__

    03/14/2022, 10:20 AM
    any updates on https://github.com/prisma/prisma/issues/5837?
    v
    m
    • 3
    • 2
  • s

    Simon

    03/14/2022, 4:51 PM
    Hey everyone! I could not find anything about indexing the referencing side's key(s) in relations with PostgreSQL in the Prisma docs. As that is something PostgreSQL doesn't automatically do (and neither does Prisma, see #3943), but often leads to huge performance improvements for large joins, I would suggest adding a corresponding advice to the docs (for example on the relations page). I would appreciate it, as I think many developers are not aware of this (multiple other ORMs create these indexes by default for the same reason). What do you think?
    n
    • 2
    • 1
  • n

    Nicholas Chiang

    03/14/2022, 5:55 PM
    Hey everyone! I'm working on Tweetscape and am trying to move over to using Prisma, but I'm not sure if your nested querying capabilities will support something like:
    Copy code
    select
          links.*,
          clusters.id as cluster_id,
          clusters.name as cluster_name,
          clusters.slug as cluster_slug,
          sum(tweets.insider_score) as insider_score,
          sum(tweets.attention_score) as attention_score,
          json_agg(tweets.*) as tweets
        from links
          inner join (
            select distinct on (urls.link_id, tweets.author_id, tweets.cluster_id)
              urls.link_id as link_id,
              tweets.*
            from urls
              inner join (
                select 
                  tweets.*,
                  scores.cluster_id as cluster_id,
                  scores.insider_score as insider_score,
                  scores.attention_score as attention_score,
                  to_json(influencers.*) as author,
                  to_json(scores.*) as score
                from tweets
                  inner join influencers on influencers.id = tweets.author_id
                  inner join scores on scores.influencer_id = influencers.id
                ${filter === 'hide_retweets' ? `where not exists (select 1 from refs where refs.referencer_tweet_id = tweets.id and refs.type = 'retweeted')` : ''}
              ) as tweets on tweets.id = urls.tweet_id
          ) as tweets on tweets.link_id = links.id
          inner join clusters on clusters.id = tweets.cluster_id
        where clusters.slug = '${params.cluster}' and expanded_url !~ '^https?:\\/\\/twitter\\.com'
        group by links.id, clusters.id
        order by ${sort === 'tweets_count' ? 'count(tweets)' : sort} desc
        limit 20;
    n
    • 2
    • 1
  • n

    Nicholas Chiang

    03/14/2022, 5:57 PM
    While there definitely is a way to get all of that nested data, I can't figure out how to aggregate and sort based on the nested select data:
    Copy code
    const links = await db.links.findMany({
        select: { // There's no way to `_sum` the nested fields from `scores`.
          urls: {
            select: {
              tweets: { // There's no way to have a nested `groupBy` here.
                select: {
                  influencers: {
                    select: {
                      scores: {
                        where: {
                          cluster_id: params.cluster,
                        },
                      },
                    },
                  },
                },
              },
            },
          },
        },
      });
1...553554555...637Latest