Multiple relations to the same table
Ramblurr opened this issue · comments
Casey Link commented
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:
- ecto does it like this: https://elixirforum.com/t/belongs-to-multiple-foreign-keys/8127/2
- ecto docs https://hexdocs.pm/ecto/Ecto.Schema.html#belongs_to/3
@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?]
]})