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

    Slackbot

    12/20/2021, 11:17 PM
    This message was deleted.
    c
    • 2
    • 3
  • a

    Anirudh Nimmagadda

    12/21/2021, 12:39 PM
    Hello all! Would anyone happen to know if filtered count is supported within relation counts? Doing it the following way results in an error:
    Copy code
    const usersWithCount = await prisma.user.findMany({
      include: {
        _count: {
          select: { posts: {where: {approved: true}} },
        },
      },
    })
  • j

    Julien Goux

    12/21/2021, 1:26 PM
    Hello all, I was searching if there is any factory generator that exists that could be generated out of prisma.schema for seeding/testing and I found this one : https://github.com/toyamarinyon/prisma-factory-generator It’s pretty interesting! Are you aware of any other project to help with strongly typed data generation during tests?
  • j

    Julien Goux

    12/21/2021, 1:28 PM
    How are you all dealing with this kind of data in your test suite? We currently manually maintain a set of “known dataset” for our tests, and it doesn’t scale, as expected 😂 So we’re now looking into factories/helpers to create datasets tailored for each test in isolation (yay parallel runs!)
    a
    • 2
    • 1
  • n

    Neo Lambada

    12/21/2021, 2:48 PM
    Copy code
    model User {
      id           Int            @id @default(autoincrement())
      method       User_method
      name         String         @db.VarChar(255)
      email        String         @unique(map: "email") @db.VarChar(255)
      createdAt    DateTime       @default(now()) @db.DateTime(0)
      updatedAt    DateTime       @default(now()) @db.DateTime(0)
      //relationships
      shops        Shop[]
      ShoppingCart ShoppingCart[]
      followedBy   FollowUser[]   @relation("follower")
      following    FollowUser[]   @relation("following")
    }
    
    model FollowUser {
      status      Boolean  @default(false)
      createdAt   DateTime @default(now()) @db.DateTime(0)
      updatedAt   DateTime @default(now()) @db.DateTime(0)
      //relationShips
      follower    User     @relation("follower", fields: [followerId], references: [id])
      following   User     @relation("following", fields: [followingId], references: [id])
      followerId  Int      @unique
      followingId Int      @unique
    }
  • n

    Neo Lambada

    12/21/2021, 2:49 PM
    i would like to keep track of followers and following. and for insert im doing something like this
  • n

    Neo Lambada

    12/21/2021, 2:49 PM
    Copy code
    const followedUser = await context.prisma.followUser.upsert({
      where: { followerId: 4, followingId: args.userId },
      update: { status: args.status },
    })
    m
    • 2
    • 47
  • n

    Neo Lambada

    12/21/2021, 2:50 PM
    if followerId and followingId exist i want to create a new record else i want to update the status
  • t

    Tyler Strout

    12/21/2021, 3:09 PM
    I started using Prisma a few weeks ago and absolutely love it. One thing I can't seems to find is how to do schema validations. For example, if I have a field that is an int between 1 and 10 characters, is there a way to attach this to the Prisma Schema? All the articles I have read say you need to use something like Joi or Zod. Any ideas?
    a
    • 2
    • 8
  • k

    kyle travelet

    12/21/2021, 4:35 PM
    Hey All, having a problem with a column that is unique and supposed to be nullable. Prisma seems to default everything to 'not null' but I dont see a keyword where to allow now.
    m
    • 2
    • 7
  • a

    arnu515

    12/21/2021, 5:11 PM
    Hello, I'm having a problem with the MongoDB connector and relations. I'm trying to get a user's organisations based on the
    members
    property, but it is just returning all organisations, even the ones the user isn't part of. Here's the code I'm using to query, and here's my
    schema.prisma
    .
  • a

    arnu515

    12/21/2021, 5:12 PM
    Code: https://www.toptal.com/developers/hastebin/zarenegiva.js Schema: https://www.toptal.com/developers/hastebin/ejijolubiw
  • a

    arnu515

    12/21/2021, 5:12 PM
    Thanks in advance for the help!
  • j

    Joshua Ramin

    12/21/2021, 7:27 PM
    Why when is logging returning null in typescript Next JS? and when I reproduce it to React JS, the data returned? I don't understand why is that happening.
  • c

    Chris Packett

    12/21/2021, 8:00 PM
    Is there a way to narrow the return type based on the arguments of this function?
    Copy code
    async getByCallbackUuid(callbackUuid: string, includeAccount = false) {
        if (includeAccount) {
          const queryIncludeAccount =
            await prismaClient.webhookSubscription.findUnique({
              where: {
                callbackUuid,
              },
              include: {
                account: true,
              },
            });
    
          return queryIncludeAccount;
        }
    
        const queryExcludeAccount =
          await prismaClient.webhookSubscription.findUnique({
            where: {
              callbackUuid,
            },
          });
    
        return queryExcludeAccount;
      }
  • c

    Chris Packett

    12/21/2021, 8:01 PM
    Ideally, if
    includeAccount
    is false, the return type would be inferred as
    Promise<WebhookSubscription | null>
    ; and when
    includeAccount
    is true, the return type would be inferred as
    (WebhookSubscription & { account: Account; }) | null
    .
    • 1
    • 1
  • a

    Anton Pokhylenko

    12/21/2021, 8:25 PM
    after updating to prisma 3.2.0 from 2.0.0 I started getting 'Prisma: command not found ' error when trying to deploy app via AWS Elastic Beanstalk. I am doing prisma generate at deploy my generate script is
    "generate:prisma": "./node_modules/.bin/prisma generate"
    also tried using
    prisma generate
    but got same error my dependencies have
    "@prisma/client": "3.2.0",
    and devDependencies have
    "prisma": "3.2.0"
    locally everything works fine does anyone know what could potentially change in this regard?
  • v

    Vasily Zorin

    12/21/2021, 10:05 PM
    Hello, I’ve just upgraded from 3.6.0 to 3.7.0 and I am getting ➜ bot git:(master) ✗ node ./bin/test.js [1] 37771 killed node ./bin/test.js
  • c

    Chip Clark

    12/21/2021, 10:26 PM
    I can't update, create or delete from a table in the database. Undefined errors error:
    Copy code
    ERROR [ExceptionsHandler] Cannot read property '$executeRawUnsafe' of undefined
    code:
    Copy code
    async deletePersonRelationship(where: Prisma.PersonRelationshipWhereUniqueInput) {
        const insert = `DELETE FROM [dbo].[PersonRelationship] WHERE PersonRelationshipID=${where.PersonRelationshipID};`;
        return this.prisma.$executeRawUnsafe(insert);
    //  return this.prisma.$executeRaw`DELETE FROM [dbo].[PersonRelationship] WHERE PersonRelationshipID=${where.PersonRelationshipID};`;
    //  the above line doesn't work either
      }
    where:
    Copy code
    { PersonRelationshipID: 359 }
    If I run the script on the SQL server, it works. Similar issue with Update and Create. With Update I tried using the internal Prisma commands:
    Copy code
    async updatePersonRelationship(params: {
        where: Prisma.PersonRelationshipWhereUniqueInput;
        data: Prisma.PersonRelationshipUpdateInput;
      }) {
        const { data, where } = params;
        const response = await this.prisma.personRelationship.update({
          data,
          where,
        });
      }
    but I get the following error:
    Copy code
    ERROR [ExceptionsHandler] Cannot read property 'personRelationship' of undefined
    If I switch to the following code:
    Copy code
    async updatePersonRelationship(params: {
        where: Prisma.PersonRelationshipWhereUniqueInput;
        data: Prisma.PersonRelationshipUpdateInput;
      }) {
        const { data, where } = params;
        console.log('\n\n\n' + JSON.stringify(data) + '\n\n\n');
        // const response = await this.prisma.personRelationship.update({
        //   data,
        //   where,
        // });
        // console.log(response);
    
        const insert = `UPDATE [dbo].[PersonRelationship] 
                        SET ActiveFromDate=$data.ActiveFromDate,
                            ModifiedBy=$ModifiedBy,
                            PKPersonID=$PKPersonID,
                            RelatedPersonID=$RelatedPersonID,
                            RelationshipTypeID=$RelationshipTypeID
                        WHERE PersonRelationshipID=$where`;
        return this.prisma.$executeRawUnsafe(insert);
      }
    I get the following error:
    Copy code
    {"ActiveFromDate":"2021-12-21T00:00:00.000Z","ModifiedBy":"MDD Admin Tool","PKPersonID":18,"RelatedPerson":285,"RelationshipTypeID":1}
    [Nest] 102196  - 12/21/2021, 2:22:32 PM   ERROR [ExceptionsHandler] Cannot read property '$executeRawUnsafe' of undefined
    I included the console log of the data to show what was passed. Again, this script works on the sql server. I am at a loss as to why I'm getting undefined errors.
  • v

    Vasily Zorin

    12/21/2021, 10:38 PM
    @Chip Clark it’s obvious.
    this.prisma
    is not defined
    c
    • 2
    • 2
  • u

    user

    12/22/2021, 8:46 AM
    Prisma Chats with Carmen Berndt

    https://www.youtube.com/watch?v=4AhO-OFM0Yg▾

    In this video, Marketing Associate Intern Nika Music interviews Carmen Berndt, who is a Working Student Engineer at Prisma's engineering team. The pair talk about university vs. company life balance. Connect with Carmen: Twitter: http://twitter.com/carmen_berndt Next: 👉 Next video: Prisma Chats w/ Alex Ruheni

    https://youtu.be/4mC03wvmKPY▾

    👉 Previous video: Prisma Chats w/ Mahmoud Abdelwahab

    https://youtu.be/2beveFa7vXY▾

    00:19- Intro 00:55 - Getting started w/ tech world 01:22 - Differences between university and company environments 01:57 - Biggest challenge 02:18 - Favorite part of working at Prisma 02:45 - Most exciting project 03:25 - Most exciting technology 04:02 - Preferred stack 04:33 - Advice for people entering tech world
  • p

    Pedia of Sunnah

    12/22/2021, 9:20 AM
    i get an error like this, When running
    findMany
    export const docs = () => {
    return db.doc.findMany()
    }
    schema:
    model Doc {
    id Int @id @default(autoincrement())
    docable_type String
    docable_id Int
    file String
    created_by Int
    updated_by Int
    deleted_at DateTime?
    created_at DateTime? @default(now())
    updated_at DateTime? @updatedAt
    title String?
    tenant Tenant? @relation(fields: [tenant_id], references: [id])
    tenant_id Int?
    @@map("docs")
    }
    Have a solution for this?
  • p

    Pedia of Sunnah

    12/22/2021, 9:21 AM
    Field doesn’t exist on enclosing type, why i get this error?
    m
    m
    • 3
    • 5
  • h

    hj yuiyui

    12/22/2021, 10:28 AM
    Hi guys i have this
    model groupevent{
    groupevent_id  Int  @id @default(autoincrement())
    website_id Int
    created_at DateTime? @default(now()) @db.Timestamptz(6)
    event_type  String   @db.VarChar(50)
    event_value String   @db.VarChar(50)
    website     website  @relation(fields: [website_id], references: [website_id])
    event event?
    }
    and this query to create a new record
    export async function createEvent(website_id, event_type, event_value) {
    return runQuery(
    prisma.groupevent.create({
    data : {
    website:{connect: {website_id: website_id}},
    event_type: event_type?.substr(0, 50),
    event_value: event_value?.substr(0, 50),
    }
    })
    )
    }
    and this is my post route if
    (req.method === 'POST') {
    if (!(await allowQuery(req))) {
    return unauthorized(res);
    }
    const { id, event_type, event_value } = req.query;
    const websiteId = +id;
    const events = await createEvent(websiteId,event_value, event_type);
    return ok(res, events);
    }
    and this how i call my post route on my front end
    const onSubmit = (dataForm: IFormValues) => {
    const idStr: string = idWebsite.toString();
    const data = {
    id: idWebsite,
    event_type : dataForm.event_type,
    event_value: dataForm.event_value
    };
    const url: string = window.apiUrl;
    `post(
    ${url}/api/website/${idStr}/events
    , data)(didnt paste the following, its useless)` and when i try to post i get this PRISMA error on my server log
    Copy code
    Argument event_type for data.event_type is missing.
    Argument event_value for data.event_value is missing.
    Any idea why ?
    m
    • 2
    • 29
  • g

    George Lewis

    12/22/2021, 11:00 AM
    Hi All, I am facing a problem and I spent more than 5 hours trying to solve it with no luck. I have a model organizationMembership as follow
    Copy code
    model OrganizationMembership {
      id          String                   @id @default(cuid())
      permissions OrganizationPermission[]
    
      dailyVerseNotification Boolean? @default(false)
    
      organization   Organization @relation(fields: [organizationId], references: [id])
      organizationId String
      profile        Profile?     @relation(fields: [profileId], references: [id])
      profileId      String?
      user           User?        @relation(fields: [userId], references: [id])
      userId         String?
    
      startDate DateTime @default(now())
      updatedAt DateTime @updatedAt
    
      meetingRoomReservationModerated MeetingRoomReservation[]
    
      @@unique([userId, organizationId])
      // @@index([profileId])
      // @@index([userId])
      // @@index([organizationId])
      // @@unique([profileId, organizationId])
    }
    and a resolver to query all the organizationMemberships as follow
    Copy code
    async organizationMemberships(
        _parent: any,
        args: OrganizationMembershipsArgs,
        ctx: ContextInterface
      ): Promise<OrganizationMembership[]> {
        const organizationMemberships = ctx.prisma.organizationMembership.findMany({
          where: {
            id: args.where?.id,
            userId: args.where?.user?.id,
            organizationId: args.where?.organizationId?.length
              ? { in: args.where.organizationId }
              : undefined,
            user: {
              profile: {
                name_search_key: {
                  contains: args.where?.name_search_key,
                  mode: 'insensitive'
                }
              }
            }
          },
          skip: args.skip,
          take: args.first
        })
    The problem is that when i run the query (Searching by OrganizationId) I only get the records that have a user entity not the rest (with null user). can anyone help?
    m
    • 2
    • 1
  • d

    Dimitri Ivashchuk

    12/22/2021, 12:30 PM
    Hey! it seems like you already provided the support for
    aggregate relations
    but I am still struggling to make it work/find the docs. Is it really implemented or still in progress?
  • v

    Victor Tr

    12/22/2021, 2:12 PM
    Hello everyone and merry christmas! Just started looking at prisma and it seems cool! I have a question about a many to many relation.
    Copy code
    model User {
      id           String               @id @default(uuid())
      Squads       UserSquadMap[] // I would like this to be an implicit maping of the actual mapped Squad. => Squad[]
      OwnedSquads  Squad[]
    }
    
    model Squad {
      id          String
      owner_id    String
      Owner       User           @relation(fields: [owner_id], references: [id], onDelete: NoAction, onUpdate: NoAction)
      Members     UserSquadMap[] // And this obviously =>  Users[]
    }
    
    // The Join Table
    model UserSquadMap {
      userId  String
      squadId String
      User    User     @relation(fields: [userId], references: [id], onDelete: Cascade)
      Squad   Squad    @relation(fields: [squadId], references: [id], onDelete: Cascade)
    
      @@id([userId, squadId])
      @@index([squadId])
      @@index([userId])
    }
    I want to directly reference the JoinTable relation entity so that I don't have nested
    includes {}
    and nested responses with irrelevant data. Right now I'm just transforming the object in the actual response, but surely there's a better way to directly reference it somehow? Is this possible? (I have been looking at
    @@map
    but no no avail, yet)
    m
    • 2
    • 6
  • m

    Mateus Silva

    12/22/2021, 2:36 PM
    Hi guys! Can anyone help me with unit testing? I followed the steps described in the docs to create the
    prismaMock
    but it's not working
    j
    • 2
    • 7
  • h

    hj yuiyui

    12/22/2021, 3:34 PM
    Hi guys, how can i insert into my database some record to test it out ? I know the query but where do i put this query ?
    n
    • 2
    • 2
  • f

    Felix Wohnhaas

    12/22/2021, 3:50 PM
    Hey Guys, A question: We have a production and staging postgresql database which is currently using Typeorm as ORM. They are using the same schema, but indices, keys, … do not have the same IDs. We would like to migrate this System to Prisma. I started introspecting the staging database, using
    prisma db pull
    . This worked, however my schema now contains all sorts of mappings to existing keys, constraints, … E.g.:
    @id(map: "PK_71a8d4792f7790deb531235496c")
    @relation(fields: [seasonId], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "FK_2725433beb670562c7ffe20b5a2")
    These mapped IDs do not exist in the production database. My question is: Can I safely remove these mappings? What are they used / needed for? When starting “fresh”, prisma also does not generate these mappings..
    • 1
    • 1
1...524525526...637Latest