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

    Jose

    10/12/2022, 7:43 PM
    Hello! Quick question about several relationships between the same models:
    Copy code
    model Account {
      id                   String           @id @default(uuid())
      name                 String
      billingAddress       Address?         @relation("billingAddress", fields: [billingAddressId], references: [id])
      billingAddressId     String?
      fulfillmentAddress   Address?         @relation("fulfillmentAddress", fields: [fulfillmentAddressId], references: [id])
      fulfillmentAddressId String?
      addresses            Address[]
    }
    
    model Address {
      id                        String    @id @default(uuid())
      name                      String
      accountBillingAddress     Account[] @relation("billingAddress")
      accountFulfillmentAddress Account[] @relation("fulfillmentAddress")
      account                   Account   @relation(fields: [accountId], references: [id], onDelete: Cascade)
      accountId                 String
    
      @@unique([name, accountId])
    }
    I'm trying to seed a database creating and connecting the Account with Addresses (an Account could have many addresses, but 2 of them are quite special and marked as
    billing
    and
    fulfillment
    addresses:
    Copy code
    {
        id: '1',
        name: 'Catalog',
        addresses: {
          create: [
            {
              id: 'Catalog-HQ',
              name: 'Headquarters',
            },
            {
              name: 'Miami Office',
            },
          ],
        },
        billingAddressId: {
          connect: { name: 'Headquarters' },
        },
        fulfillmentAddress: {
          connect: { name: 'Miami Office' },
        },
      }
    I'm getting an error
    Copy code
    Unknown arg `name` in data.fulfillmentAddress.connect.name for type AddressWhereUniqueInput. Did you mean `id`? Available args:
    type AddressWhereUniqueInput {
      id?: String
      name_accountId?: AddressNameAccountIdCompoundUniqueInput
    }
    which I'm suspecting is somehow related to the
    @@unique([name, accountId])
    on the addresses (but also seems necessary in order not to repeat names on the same account). Any clue about what's wrong?
    ✅ 1
    n
    • 2
    • 2
  • a

    abdoaligomaa107

    10/13/2022, 5:52 AM
    i have a question about shadow database : 1- why should i use shadow database ? for what , what it should do to help me? 2- i know that i use shadow db if i using cloud database ,and did't use it if i use local database ,why?! or the prisma generate one if i using local db?
    👀 1
    ✅ 1
    n
    • 2
    • 1
  • j

    John Carl Edcel Manuel

    10/13/2022, 5:57 AM
    Hello everyone! Can somebody explain this? When formatting date from prisma. 2022-10-13T054047.768000+00:00 -> Oct 13, 2022 1:40 PM ------------ This is original data --------- -----formatted date----- frontend code
    _<_td _className=_"py-4 pl-3"_>_
    _{service.added_date} -> {dayjs(service.added_date).format(_"MMM D, YYYY h:mm A"_)}_
    _</_td_>_
    prisma
    _added_date_  DateTime  _@default_(now())
    👀 1
    n
    v
    • 3
    • 5
  • n

    Nurul

    10/13/2022, 6:32 AM
    Hi @Jaskaran Yadav 👋 Can you please update to the latest version of Prisma i.e.
    4.4.0
    and check if you get the same error?
    j
    • 2
    • 3
  • d

    David Ilizarov

    10/13/2022, 10:17 AM
    Hi all, I'm trying to
    updateMany
    but with unique data per row... I'm beginning to think this isn't possible with that API. Should I instead be using
    upsert
    API for this?
    👀 1
    n
    • 2
    • 1
  • d

    David Ilizarov

    10/13/2022, 10:33 AM
    Hmm... might have to use
    prisma.$transaction
  • r

    Richard Jones

    10/13/2022, 10:55 AM
    Hi, I'm trying to setup Prisma in an AWS lambda with multiple schemas - is there a way I can tell the PrismaClient class where to find the schema.prisma file? Even if I set the Dockerfile's workdir to /tmp then I still get an error saying /var/task/schema.prisma not found.
    ✅ 1
    n
    • 2
    • 2
  • k

    Kay Khan

    10/13/2022, 11:42 AM
    Hi friends i would to introspect my database but im only interested in a handful of tables (4 or 5). Is there some wway to specify the name of those tables in the
    npx prisma db pull
    command?
    ✅ 1
    r
    • 2
    • 4
  • a

    Andrea Romanello

    10/13/2022, 4:39 PM
    ✌️ Hi everyone, I'm starting to develop a new app with fastify and I want to use Prisma for first time as ORM. The setup working well and and the models are very easy to use and everythink working well. Now I want to setup some unit test, my preferred setup is to use TAP as test framework. Anyone have some suggestion how to mock Prisma with TAP? Because on the guide is suggested to use Jest but I doesn't have a very good relations with it.
    👀 1
    n
    • 2
    • 3
  • t

    Ty-Lucas Kelley

    10/13/2022, 5:14 PM
    Question about
    prisma migrate
    - was looking around for an option to do a 'dry run' of a migration before it's deployed, but didn't come across anything. Our goal is to be able to validate a migration in development against our production database(s) before that code is ever merged and deployed, so we don't have to wait for it to fail, then go through the process of rolling it back, editing the migration, re-deploying, etc..
    👀 1
    n
    a
    • 3
    • 3
  • h

    Hayley Dawson

    10/13/2022, 6:19 PM
    Hey everyone, Question and I may just be reading the documentation wrong. Is there a way to sort a query on a relationship, passing a where clause to the relationship? (or a work around that does not mean dropping to a rawQuery to do that?) Example would be like, If I have books, and books have reviews, reviews are tied to a user. I want a list of books, sorted by whether I have reviewed them or not (ie by the reviews table where userid = mine)
    ✅ 1
    n
    • 2
    • 2
  • s

    Sebastian Gug

    10/13/2022, 8:24 PM
    how are you guys applying prisma migrations in a VPC on GCP? anyone using a "bastion" cloud function? or something like that? is it possible to apply them on-demand via calling an endpoint?
    💬 1
    n
    • 2
    • 1
  • d

    David Ilizarov

    10/13/2022, 8:32 PM
    Is there a way to
    createMany
    while one of the fields is like a counter? For example, I need something like this:
    Copy code
    prisma.invoice.createMany({
      data: [
        { 
          name: invoice.name, 
          billerId: user.id, 
          invoiceNumber: prisma.invoice.count({where: { billerId: user.id }}) + 1
        }, 
        ... 
      ]
    })
    Perhaps there is a way for me to get all prisma.invoice.counts easily first.
    Copy code
    prisma.invoice.groupBy({
      by: ['billerId'],
      _count: true
    })
    From there, I could smartly create the invoiceNumber... I'd probably perform this in an interactive transaction. My only problem is that during this groupBy/createMany combo, I want to ensure that the tables remained locked or that I can assure the actions are atomic — I don't want invoices created that would invalidate the invoiceNumber (as I have a unique constraint on [billerId, invoiceNumber]) Does something like the following suffice for that?
    Copy code
    prisma.$transaction(async (tx) => {
      const invoiceCountsForBiller = await tx.invoice.groupBy({
        by: ['billerId'],
        _count: true
      })
    
      await tx.invoice.createMany({
        data: {[
          {
            // ... incorporate invoiceCountsForBiller into logic
          }
        ]}
      })
    })
    • 1
    • 1
  • a

    Amos Bastian

    10/13/2022, 10:11 PM
    I think I am being super dumb, but I have a many-to-many relationship of
    Entry
    to
    Campaign
    . I want to find all entries connected to a given campaign. I thought I could just do
    Copy code
    const entries = await ctx.prisma.entry.findMany({
      where: {
        campaigns: { every: { id: { equals: campaignId } } },
      },
    });
    but this is returning entries that aren’t connected to any campaigns as well 😕 According to the docs this should only return every
    Entry
    that has a
    Campaign
    with the given id, or am I wrong? I can solve this by adding
    some: {}
    to the filter (to exclude every
    Entry
    without a
    Campaign
    , but this seems unnecessary to me)
    ✅ 1
    t
    n
    • 3
    • 4
  • d

    David Ilizarov

    10/13/2022, 10:23 PM
    Ran into this bug: https://github.com/prisma/prisma/issues/15785 Seems simple enough — am I missing something?
  • d

    David Ilizarov

    10/13/2022, 11:28 PM
    Have this situation:
    Copy code
    let details: JsonValue | Prisma.DbNull = Prisma.DbNull;
    
    // object.details is JsonValue
    object.details = details === Prisma.DbNull ? null : details;
    
    // Error: Type 'JsonValue | DbNull' is not assignable to type 'JsonValue'.
    // Type 'DbNull' is not assignable to type 'JsonValue'
    I don't see Prisma acknowledging this in documentation anywhere.
    Copy code
    object.details = details instanceof Prisma.NullTypes.DbNull ? null : details;
    
    // This works ^^^
    Not sure I like the version that works for TypeScript. Thoughts?
    💬 1
    ✅ 1
    v
    • 2
    • 5
  • j

    João Vitor Casarin

    10/14/2022, 12:24 PM
    Hey folks, why aren’t the client api methods’ responses standardized? Example, the
    create
    method does not explicitly throw an error in the Docs, but
    update
    and
    delete
    does. The method
    findFirst
    has a second option that’s
    findFirstOrThrow
    . Why aren’t all of these standardized, like making all of them throw an error when failed? That would be better for using I guess.
    👀 1
    ✅ 1
    n
    • 2
    • 5
  • s

    Satish

    10/14/2022, 12:49 PM
    I'm new to Prisma. Prisma has definitely saved my time, but I'm also running into couple of problems with querying. Here is a specific one: (Prisma + MongoDB + Remix) I've a ticket collection, and it has a reply field which is an array of objects. reply object has agentId field, which is mapped to id of Agent collection. Agent collection has agents name and photo. Now how do I write a query to fetch a document from ticket collection, along with name and photo of the agent in the agentId present in reply field of Ticket collection. I tried searching for it online, but I'm still confused as to how to do that. Any help is much appreciated.
    👀 1
    r
    • 2
    • 2
  • j

    Jay Bensal

    10/14/2022, 6:40 PM
    I’m running
    npx prisma db push
    to generate a schema against a local MySQL database running in a docker container. I’m getting a no database selected error… which is a bit odd to me, esp given that this exact command was working a week ago. any thoughts on how I can specify a db?
    Copy code
    jay@Jays-Macbook-Air beam % npx prisma db push
    Environment variables loaded from .env
    Prisma schema loaded from prisma/schema.prisma
    Datasource "db": MySQL database "readyset_beam" at "127.0.0.1:3307"
    Error: No database selected
       0: sql_migration_connector::sql_database_step_applier::apply_migration
                 at migration-engine/connectors/sql-migration-connector/src/sql_database_step_applier.rs:11
       1: migration_core::state::SchemaPush
                 at migration-engine/core/src/state.rs:274
    👀 1
    ✅ 1
    r
    • 2
    • 4
  • a

    AJ Holloway

    10/14/2022, 10:54 PM
    This is so strange. I’m running a query and then mapping the result with findUnique to get the user afterwards. For some reason though, it’s returning null users.
    Copy code
    const scorers = await DBConn.recognition_logger.groupBy({
                by: ['receiver_id'],
                _sum: {
                    amount: true,
                },
                orderBy: {
                    _sum: { amount: 'desc' },
                },
                where: {
                    OR: [{ action: 'gave_points' }, { action: 'approve_claimable_award' }, { action: 'custom_award_send' }],
                    users_recognition_logger_receiver_idTousers: {
                        active: true,
                    },
                    amount: { gt: 0 },
                    company_id: res.locals.requestingUser.companies.id,
                    created: {
                        gte: DateTime.now().startOf('month').startOf('day').toUnixInteger(),
                        lte: DateTime.now().endOf('month').endOf('day').toUnixInteger(),
                    },
                    hidden_from_leaderboard: false,
                    valid: true,
                    type: {
                        equals: 'Regular',
                    },
                },
            });
            scorers.map(async (e) => {
                const user = await DBConn.users.findUnique({ where: { id: e.receiver_id } });
                console.log(user);
            });
    receiver_id is a user’s id.
    Copy code
    SELECT [*] FROM "public"."users" WHERE "public"."users"."id" IN ($1,$2) OFFSET $3
    Params: [157359532448138,165341040401209,0]
    Duration: 11ms
    null
    null
    Interestingly, when I copy this into pgAdmin, it works just fine. Any idea why this is happening? Apologies for the long message, I removed all the fields for security and length’s sake. (Yes I know that I’m mapping and it returns a new object. But the output from the Query in my console is null,null)
    👀 1
    n
    • 2
    • 3
  • p

    prisma chobo

    10/14/2022, 11:07 PM
    What am I getting this error all of sudden??
    Copy code
    "\nInvalid `prisma.user.findUnique()` invocation:\n\n\nQuery engine library for current platform \"darwin-arm64\" could not be found.
    r
    • 2
    • 1
  • p

    prisma chobo

    10/14/2022, 11:08 PM
    it's been working good without any issue. Didn't change single line of codes...
  • p

    prisma chobo

    10/14/2022, 11:08 PM
    Just updated version from 4.2.0 to 4.4.0
  • p

    prisma chobo

    10/14/2022, 11:10 PM
    I tried with
    bindaryTargets = ["native", "darwin"]
    and
    bindaryTargets = ["native"]
    still not working
    👀 1
    r
    • 2
    • 2
  • s

    Slackbot

    10/15/2022, 6:56 PM
    This message was deleted.
  • m

    Morten Barklund

    10/15/2022, 7:07 PM
    Just wrote a long post about how group by aggregations didn't work, and while I was typing it up, I realized my attribute was a string, so of course it can't be summed! Sorry, ignore me, but hi! 👋
    👋 2
    ✅ 1
    prisma rainbow 1
    🙌 2
    n
    • 2
    • 1
  • u

    ut dev

    10/15/2022, 7:30 PM
    Is there an existing bug for Prisma related to renaming columns, this issue happens all the time after renaming columns
  • u

    ut dev

    10/15/2022, 7:30 PM
    Basically it still tries to look for the old named column
  • u

    ut dev

    10/15/2022, 7:30 PM
    not sure how to fix that
    ✅ 1
    n
    • 2
    • 4
  • n

    nilsso

    10/15/2022, 8:27 PM
    Is there a good mechanism in
    prisma migrate
    for migrating data from one "old" database to the
    schema.prisma
    datasource "new" database? I'd love to do something like
    Copy code
    INSERT INTO `new`.`Foo`
    SELECT `bar`
    FROM `old`.`Foo`;
    Okay it seems it really was that easy, nevermind!
    ✅ 1
    n
    • 2
    • 1
1...632633634...637Latest