Earlier, we learned that ORM tends to play the role of bridge between RDB and Object language. ORMs have introduced several issues (less type safety, complicated queries,Mismatch between the data model and the code).The prisma addresses these shortcomings, focused on type safety and development productivity.
"On top of being an ORM, it provide us with a complex tool kit for accessing database.
npm install -g prisma // without install we can use npx
npm install @prisma/client
Creating prisma directory, make .env file and schema.prisma files in the project root.
prisma is mainly consisted with 3 main factors.
schema
.prisma extention file defining schema as intuitive language and simplified. client
It is the auto generatated Type-safe database query builder based on the Prisma Schema.
It commonly use when interacting with a database from Node.js or TypeScript code.
* without complicated queries or raw query strings, we can use HTTP methods.
Autocomplete and type inspection.
prisma Migrate
It is the managemnet tool to adopt modifcations.
when developer updates the schema file, Prisma Migrate tracks changes of database, generates essential migration scripts.
It makes data schema synchronization easy between the development and production environmnet.
// μμ: schema.prisma νμΌ
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[] // Userμ Postλ 1:N κ΄κ³
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int // μΈλ ν€
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
import {PrismaClient} from "@prisma/client";
const prisma = new PrismaClient
async function main(){
// create new user
const newUser = await prisma.user.create({
data:{
name: 'Alice',
email: 'Alice@email.com',
},
})
console.log('created user:'newUser);
// access all users
const allUser = await prisma.user.findMany();
console.log('
}
When you visualise Prisma Table, it is easy for developer to confuse understanding or writing code. So I am fully recommend to use 3 logical statement and relationships...
Example:
Product can have multiple tags, also the tags can have multiple tags
there is Many - many relationship between products and tags.
this join stores pairs of productID and TagID to represent relation.