Nested writes in Prisma orm - prisma

My schema looks like this:
model Transaction {
id BigInt #id #default(autoincrement())
description String? #db.VarChar(256)
category Category? #relation(fields: [categoryId], references: [id])
createdById Int #map("fk_created_by")
createdBy UserAccount #relation("category_fk_created_byTouser_account", fields: [createdById], references: [id]
}
model Category {
id Int #id #default(autoincrement())
name String #db.VarChar(40)
categoryFilters CategoryFilter[]
}
model CategoryFilter {
id BigInt #id #default(autoincrement())
words String #db.VarChar(255)
categoryId Int? #map("fk_category_id")
}
My question is why this works:
await prisma.workspaceTransaction.create({
data: {
description: 'any',
createdBy: {
connect: {
id: 1
}
},
category: {
create: {
name: 'Este é um teste',
createdById: 1,
categoryFilters: {
createMany: {
data: [
{
words: 'Novo teste'
}
]
}
}
}
}
}
})
And this not?
await prisma.workspaceTransaction.create({
data: {
description: 'any',
createdById: 1,
category: {
create: {
name: 'Este é um teste',
createdById: 1,
categoryFilters: {
createMany: {
data: [
{
words: 'Novo teste'
}
]
}
}
}
}
}
})
The only difference between those two examples is in createdBy command. And i can create Transaction without nested objects with createdById argument. Any one know why this works this way? Or there is something i am missing?
The error given is:
Unknown arg createdById in data.createdById for type TransactionCreateInput

In the second example, you are directly writing a foreign key (createdById) which is considered unsafe, what if there is no UserAccount corresponding to createdById.
While using connect in the first example it would throw an error if Prisma cannot find an UserAccount corresponding to id 1.
First example is the preferred approach.

Related

Prisma connect product to users with quantity

I have a list of products, and a list of users and I want to be able to relate users to what products they have but also what quantity they have of each product.
I've setup my user schema like this:
model users {
id String #id #default(uuid())
email String #unique
password String
test_products test_products[]
users_to_test_products users_to_test_products[]
}
I've implicitly stated the relation so that I can add in a quantity field
model users_to_test_products {
users users #relation(fields: [user_id], references: [id])
user_id String
test_products test_products #relation(fields: [product_id], references: [product_id])
product_id String
quantity Int
##id([user_id])
}
and I've setup my product list like this:
model test_products {
product_id String #id
name String?
users users[]
users_to_test_products users_to_test_products []
}
I assumed I could make an update call, connecting the user to the test product and passing in the quantity but it seems that I can't and my approach is completely wrong.
await prisma.users.update({
data: {
test_products: {
connect: UserProducts.map((product) => {
return {
product_id: product.product_id,
quantity: product.quantity
}
}),
},
},
where: {
id: userId
},
})
note: UserProducts is just an object array eg [{ product_id: "tTer3434", quantity: 8 }]
Can anyone point me in the right direction on the approach I need to take please?

Prisma constraint not available

I`m using Prisma with NestJS and PostgreSQL
In my schema.prisma i have this
model User {
userId Int #id #default(autoincrement())
firstName String? #db.VarChar(25)
lastName String? #db.VarChar(25)
login String #unique #db.VarChar(60)
email String #unique
password String
createdAt DateTime #default(now())
updatedAt DateTime #updatedAt
role Role? #default(ADMIN)
createdUsers User[] #relation("createdBy")
createdBy User? #relation("createdBy", fields: [creatorId], references: [userId])
creatorId Int?
}
enum Role {
ADMIN
MANAGER
WAREHOUSE
USER
}
So when a make create request like this
{
login: "A",
email: "A",
password: "A"
}
it saves in DB - that`s ok. By after the same request i get this error "Unique constraint failed on the (not available)". So shouldn't there be a not unique column name instead of (not available) or that is ok case? Where am i wrong?
I was trying drop table Users and make different unique combs, don`t know what else i can do...
UPD:
async create(createUserDto: CreateUserDto) {
return this.prisma.user.create({
data: {
...createUserDto
}
})
}
export class CreateUserDto {
#IsNotEmpty()
login: string;
#IsNotEmpty()
#IsEmail()
email: string;
#IsNotEmpty()
#MinLength(6)
password: string;
}
UPD 2.0
Finally, moved to TypeORM, it is bug like #num8er mentioned
https://github.com/prisma/prisma/issues/10829
Ty for all the replies

Prisma relations: define relations without using "connect" syntax

I use Postgres with Prisma and I want to ask if there is a way to use upsert or create functions and define relations without the connect field.
I have these models:
model User {
id Int #id #default(autoincrement())
posts Post[]
}
model Post {
id Int #id #default(autoincrement())
author User #relation(fields: [authorId], references: [id])
authorId Int // relation scalar field (used in the `#relation` attribute above)
}
and I want to do something like this:
prisma.Post.upsert({where: { authorId: 12 }, update: {}, create: { authorId: 12 })
assuming User with ID 12 does exists in the DB I want it to create a new record successfully but it fails because it wants it in this syntax:
prisma.Post.upsert({where: { authorId: 12 }, update: {}, create: { author: { connect: { id: 12}}}})
is this achievable somehow?
Thanks.

Return properties are null value when I get by Id

I've just create a new spring boot application with GraphQL + MongoDB. I can retrieve an array from database, but querying by id does not work. Property is null. But I see the data correctly while debugging. It like GraphQL is not capable to match the query with the value return.
I'm new at using GraphQL, it's probably little details...
Schema GraphQL
schema {
query: Query
}
type Query {
datasets: [Dataset]
dataset(id: String): Dataset
}
type Dataset {
id: String
name: String!
}
Dataset class look like this:
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
#Document(collection = "datasets")
public class Dataset {
private ObjectId id;
private String name;
}
When I query with:
{
datasets{
name
}
}
I get this:
{
"datasets": [
{
"name": "My Dataset"
}
]
}
But when I query with:
{
dataset(id: "5dab4ec97ff755534437c8bc"){
name
}
}
I get this:
{
"dataset": null
}
The id is ok:

Mongo DB: how to $addToSet custom type element using C# Official driver

I have a document with an array of custom type elements:
{
_id: 'id',
name: '',
customElements: [
{ _id: 'id',
name: 'name'}
]
}
In C# i have corresponding classes:
public class CustomElement
{
[BsonId]
public ObjectId id { get; set; }
public string name { get; set; }
CustomElement ()
{
id = ObjectId.GenerateNewId();
}
}
Using c# official driver, I try to create an Update statement:
var update = Update.AddToSet("customElements", new CustomElement { name = "name"});
But it shows that it is not assignable to BsonValue. How to convert it and $addToSet?
Option 1, via Wrapped methods that was come with driver version 1.0:
Update.AddToSetWrapped<CustomElement>("customElements",
new CustomElement() { name = "name"); //c# driver >= 1.0
Option 2, convert your class to BsonValue yourself via ToBsonDocument() extention method.
Update.AddToSet("customElements", new CustomElement() { name = "name"}.ToBsonDocument());
Hope this helps.