Eric
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    本文會介紹 prisma 這個非常好用的 ORM,比起 TypeORM 的語法,prisma 可謂是非常簡單易懂,程式碼的可讀性也相當之高。以下將會介紹 prisma model 的寫法和不同 relation 的 CRUD。 ## One To Many 情境如下: 在遊戲攻略平台中,發文前需要選定一個遊戲版,而遊戲版需要由版主來創建,每個貼文需要歸屬於一個遊戲版,一個遊戲版可以有多個文章,因此relation為一對多 1. 版主創建遊戲版 2. 選擇某個遊戲版發文 #### Game model (parent) ```typescript= model Game { id Int @default(autoincrement()) @id name String posts Post[] } ``` #### Post model (children) ```typescript= model Post { id Int @default(autoincrement()) @id name String body String game Game @relation(fields: [gameId], references: [id]) gameId Int } ``` #### Create game 版主創建遊戲版 ```typescript= async createGame(data: CreateGameDto) { const game = await this.prismaService.game.create({ data }) return game } ``` #### Create Post 選擇某個遊戲版發文 ```typescript= async createPost(data: CreatePostDto) { const result = await this.prisma.post.create({ data }); return result; } ``` #### CreatePostDto 從 DTO 中可以看到我們是通過 post model 中的 fields 去進行關聯,且我們定義 fiels 為 gameId,因此在create 和 update 時透過 gameId 這個屬性進行關聯操作即可。 authorId 可以從 jwt token中解析 ```typescript= class CreatePostDto { name: string; body: string; authorId: number; gameId: number; } ``` #### Get Post ```typescript= async getPosts() { const result = await this.prisma.post.findMany({ include: { game: { select: { name: true } } }, } ``` #### Update Post ```typescript= async updatePostById(id: number, data: UpdatePostDto) { const result = await this.prisma.post.update({ where: { id }, data: { ...data, }, }); return result; } ``` ## Many To Many 情境如下: 在遊戲攻略平台中,使用者可以發布文章,並且可以對文章加註tag,如 movie、foods 等等。一個 post 可以有多個 tag ,一個 tag 也可以在多個文章中出現,因此 relation 為多對多。在 prisma 中有兩種設計模式,一種是在兩個 table 中再使用一個多對多 table 作為中介將兩者關聯起來,另外也可以在 model 中直接用 [ ] 代表兩者為多對多關係,寫起來甚至比一對多更簡潔。 1. 創建文章時加上兩個tag 1. 透過 tag 或 name 來查詢文章 2. 其他使用者想要為文章新增 tag 3. 後來後悔了想要刪掉其中一個 tag #### Post ```typescript= model Post { id Int @default(autoincrement()) @id name String body String tags Tag[] } ``` #### Tag ```typescript= model Tag { id Int @default(autoincrement()) @id name String @unique posts Post[] Games Game[] } ``` #### Create Post 創建文章時就指定 tag 透過以下的寫法便可以將data中的tag和post給關聯起來,connectOrCreate在tag不存在時可以創建tag並建立關聯,存在時則直接關聯,因為結構比較複雜,所以在create之前先將data 中的tag array給整理成規定的格式。 ```typescript= async createPost(data: CreatePostDto) { const result = await this.prisma.post.create({ data: { ...data, tags: { connectOrCreate: data.tags.map((tag) => { return { where: { name: tag }, create: { name: tag } }; }) }, }, }); return result; } ``` 這些程式在背後執行的SQL長這樣: 重要ㄟ,next generation orm,prisma會幫忙檢查tag是否存在 ```sql= // 輸入的tag存在時 BEGIN INSERT INTO "public"."Post" ("name","status","body","slug","gameId","authorId","views") VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING "public"."Post"."id" SELECT "public"."Tag"."id" FROM "public"."Tag" WHERE ("public"."Tag"."name" = $1 AND 1=1) OFFSET $2 INSERT INTO "public"."_PostToTag" ("A","B") VALUES ($1,$2) ON CONFLICT DO NOTHING SELECT "public"."Post"."id", "public"."Post"."name", "public"."Post"."status", "public"."Post"."body", "public"."Post"."slug", "public"."Post"."gameId", "public"."Post"."authorId", "public"."Post"."views" FROM "public"."Post" WHERE "public"."Post"."id" = $1 LIMIT $2 OFFSET $3 COMMIT ``` ```sql= // 輸入的tag不存在時 BEGIN INSERT INTO "public"."Post" ("name","status","body","slug","gameId","authorId","views") VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING "public"."Post"."id" SELECT "public"."Tag"."id" FROM "public"."Tag" WHERE ("public"."Tag"."name" = $1 AND 1=1) OFFSET $2 INSERT INTO "public"."Tag" ("name") VALUES ($1) RETURNING "public"."Tag"."id" INSERT INTO "public"."_PostToTag" ("A","B") VALUES ($1,$2) ON CONFLICT DO NOTHING SELECT "public"."Post"."id", "public"."Post"."name", "public"."Post"."status", "public"."Post"."body", "public"."Post"."slug", "public"."Post"."gameId", "public"."Post"."authorId", "public"."Post"."views" FROM "public"."Post" WHERE "public"."Post"."id" = $1 LIMIT $2 OFFSET $3 COMMIT ``` #### Get posts 透過 tag 或 name 來查詢文章 1. post `name` like postName, 2. tag 為 whereIn [ 'tag1' , 'tag2'] 透過這邊的例子就可以看出 prisma 能使用相對SQL及TypeORM來說,可讀性較高的語法來完成複雜的查詢。在撰寫語句時也可以直接查看source code的 input type 來撰寫。 ```typescript= async getPosts(tags: Array<string>, postName) { const result = await this.prisma.post.findMany({ include: { tags: true, }, where: { name:{ contains: postName // LIKE %postName% }, tags: { some: { // orWhere andWhere name: { in: tags, // whereIn }, }, }, }, }); } return result; } ``` raw sql ```sql= SELECT "public"."Post"."id", "public"."Post"."name", "public"."Post"."status", "public"."Post"."body", "public"."Post"."slug", "public"."Post"."gameId", "public"."Post"."authorId", "public"."Post"."views" FROM "public"."Post" WHERE ("public"."Post"."name"::text LIKE $1 AND ("public"."Post"."id") IN (SELECT "t0"."A" FROM "public"."_PostToTag" AS "t0" INNER JOIN "public"."Tag" AS "j0" ON ("j0"."id") = ("t0"."B") WHERE ("j0"."name" IN ($2) AND "t0"."A" IS NOT NULL))) OFFSET $3 SELECT "public"."_PostToTag"."A", "public"."_PostToTag"."B" FROM "public"."_PostToTag" WHERE "public"."_PostToTag"."A" IN ($1) SELECT "public"."Tag"."id", "public"."Tag"."name" FROM "public"."Tag" WHERE "public"."Tag"."id" IN ($1,$2) OFFSET $3 SELECT "public"."Game"."id", "public"."Game"."name" FROM "public"."Game" WHERE "public"."Game"."id" IN ($1) OFFSET $2 ``` #### Add tags 其他使用者想要為文章新增 tag 其實跟create post大同小異,也是用createOrCreate來和tag進行關聯。 ```typescript= async addTagToPost(id: number, tags) { const tagsData = tags.map((tag) => { return { where: { name: tag }, create: { name: tag } }; }); const result = await this.prisma.post.update({ where: { id }, data: { tags: { connectOrCreate: tagsData, }, }, }); return result; } ``` raw sql ```sql= BEGIN SELECT "public"."Post"."id" FROM "public"."Post" WHERE ("public"."Post"."id" = $1 AND 1=1) SELECT "public"."Tag"."id" FROM "public"."Tag" WHERE ("public"."Tag"."name" = $1 AND 1=1) OFFSET $2 INSERT INTO "public"."Tag" ("name") VALUES ($1) RETURNING "public"."Tag"."id" INSERT INTO "public"."_PostToTag" ("A","B") VALUES ($1,$2) ON CONFLICT DO NOTHING SELECT "public"."Post"."id", "public"."Post"."name", "public"."Post"."status", "public"."Post"."body", "public"."Post"."slug", "public"."Post"."gameId", "public"."Post"."authorId", "public"."Post"."views" FROM "public"."Post" WHERE "public"."Post"."id" = $1 LIMIT $2 OFFSET $3 COMMIT ``` #### Update 後悔了想要刪掉其中一個tag,這邊採用的做法是直接把tag刪光再重新加回去 ```typescript= async updatePostById(id: number, data: UpdatePostDto) { const tagsData = data.tags.map((tag) => { return { where: { name: tag }, create: { name: tag } }; }); const result = await this.prisma.post.update({ where: { id }, data: { ...data, tags: { disconnect: { name: ... }, connectOrCreate: tagsData, }, }, }); return result; } ``` 使用prisma語法時也可以直接查看input type來查找適合的語法,prisma的可讀性很高,因此透過這個方式幾乎不用去查文檔。 ![](https://hackmd.io/_uploads/rJRvVDy_2.png)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully