Payload CMS 美麗的錯誤

May 04, 2025

前言

前一篇說道 Payload CMS 沒有平常用的 多對多關聯,在官方文件裡面提到 Bi-directional relationships

The relationship field on its own is used to define relationships for the document that contains the relationship field, and this can be considered as a "one-way" relationship. For example, if you have a Post that has a category relationship field on it, the related category itself will not surface any information about the posts that have the category set.

參考

所有的關聯都是單向的,習慣使用的多對多關聯都會提到一個 中間表,會記錄雙邊的 id,像是 user_idattendance_id ,但想想多對多的 中間表 不也是兩組 一對多所完成的,等等就來用既有的功能完成 多對多 目的。

使用 Join Fields

參考

以出席(attendance)與人員(user)為例。

attendances

設定一個關聯跟 users collection 是一對多

fields: [ { name: 'users', type: 'relationship', relationTo: 'users', label: '參與者', hasMany: true, required: false, }, ]

他就會自動產生一個 table attendances_rels

attendances_rels

欄位會有

  • id
  • order
  • parent_id
    紀錄 attendance的 id
  • path
    寫著 users
  • users_id
    紀錄 user 的 id

此時這張表跟 一對多 沒有差異。

users

此時這邊的 type 要使用 joincollection 要寫的是要 join 的對象 collection attendanceson 則是寫自己的 collection 名稱 users,他就會去參照 attendances_rels 去做 join。

fields: [ { name: 'relatedAttendances', type: 'join', label: '出席紀錄', collection: 'attendances', on: 'users', }, ]

結語

覺得 Payload CMS 應該在文件上寫一個多對多關聯 (Many to Many) 的說明,告知設計理念與用法,不然在第一次看文件,很容易用往常的想法來寫,本來誤會他沒有多對多關聯,真的是一個美麗的錯誤。

Ekman Hsieh

文字工作者,寫作時間常常在人類與電腦之間拉鋸,相信閱讀,相信文字與思想所構築的美麗境界