modelling multiple many-to-many relationships in datomic

前端 未结 2 1718
星月不相逢
星月不相逢 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:06

    Let's first look at the simpler case where you have a one to many relationship between to kinds of entities (in your case users and comments):

    user ---- * comment
    

    You can choose to model this by letting each comment point to exactly one user, by means of an attribute, say :comment/user of type :db.type/ref.

    This would be a natural model, as a comment could have at most one user. We say that the cardinality is at most 1, ie. the count of values (in this case references to users) cannot exceed 1.

    This can be specified in the schema with :db/cardinality :db.cardinality/one, which is in fact the default, so we do not have to spell it out explicitly.

    Note that since Datomic entities are not typed, it is not possible to enforce an actual cardinality of 1, ie. any attribute can be absent. (Entities have implicit types through their actual attibutes. The maintenance and interpretation of these is entirely up to your application)

    If on the other hand you want any comment to be applicable to more than one user, you have a many-to-many relationship:

    user * ---- * comment
    

    This can be achieved by allowing the attribute :comment/user to be of :db/cardinality :db.cardinality/many, ie. by allowing multiple references from comments to users.

    In this way each user can be referenced by multiple comments and each comment can reference multiple users.

    You could equally opt to have references of cardinality many on the users instead of on the comments.

    I hope this is sufficiently clear to help getting you started :)

提交回复
热议问题