modelling multiple many-to-many relationships in datomic

前端 未结 2 1722
星月不相逢
星月不相逢 2021-02-05 20:23

Maybe I\'m still thinking sql but I\'m having trouble writing the datomic schema for a simple blog. I don\'t really understand the :db/cardinality attribute and wh

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-05 21:07

    Look at the following diagram and read the full code sample (schema, sample data and queries) at https://gist.github.com/a2ndrade/5651419. It should help you understand how to model data in Datomic.

    Datomic Schema: Blog

    Querying

    Note that some relationships are not explicitly modeled because relationships in Datomic are bidirectional and because you can retrieve the rest of the information using simple Datalog queries. For example, the query:

    (d/q '[:find ?cid ?c
       :in $ ?u
       :where
       [?uid :user/username ?u]
       [?aid :article/category ?cid]
       [?aid :article/author ?uid]
       [?cid :category/name ?c]]
     (d/db conn) "john.smith")
    

    finds all the category ids -and their names- that a user ("john.smith") has written articles for.

    Containment Relationships

    An important modeling decision is to have articles point to comments and mark the relationship as :db/isComponent since comments should not exist on their own but as part of an article. Datomic will make sure to retract all comments associated with an article if the article itself is retracted.

    Enforcing Business Rules

    If you want to enforce application-specific consistency rules (e.g. articles and comments must have a author, comments must be of certain length, etc) you need to use database functions. They run inside the transactor and can atomically enforce arbitrary constrains, aborting transactions that don't comply with them.

提交回复
热议问题