kwrooijen / gungnir

A fully featured, data-driven database library for Clojure.

Home Page:https://kwrooijen.github.io/gungnir/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Multiple relations to the same table

Ramblurr opened this issue · comments

Consider the case when you have a user model and a document model.

Each document has an author-id which is a foreign key to the user table, and a reviewer which is also a foreign key to the user table. This results in multiple belong-to relations referencing the same table (user).

As discussed in slack:

@kwrooijen suggested a format like this:

{:belongs-to {:document/author  {:model :user :through :document/author-id}}}
{:has-many   {:document/authors {:model :user :through :user/document-id}}}
{:has-one    {:document/authors {:model :user :through :user/document-id}}}

So, the example given at the top would look like:

(model/register!
  {:user
   [:map
    [:user/id {:primary-key true :auto true} int?]]})

(model/register!
  {:document
   [:map {:belongs-to {:document/author   {:model :user :through :document/author-id}
                       :document/reviewer {:model :user :through :document/reviewer-id}}}
    [:document/id {:primary-key true :auto true} int?]
    [:document/author-id int?]
    [:document/reviewer-id {:optional true} int?]
    ]})