How to model an entity with many children in Sorm?

前端 未结 1 520
不知归路
不知归路 2020-12-18 12:40

I have a Workspace and Document entities, with the idea that a workspace can contain zero, one, or more documents. My first approach to model this

相关标签:
1条回答
  • 2020-12-18 13:26

    Easy peasy! You define them unrelated:

    case class Workspace ( name : String )
    case class Document ( ... )
    

    Then you choose a way you wish them to be linked. I see two.

    Variant #1

    case class WorkspaceDocuments 
      ( workspace : Workspace, documents : Seq[Document] )
    

    And get all documents of a workspace like so:

    Db.query[WorkspaceDocuments]
      .whereEqual("workspace", theWorkspace)
      .fetchOne()
      .map(_.documents)
      .getOrElse(Seq())
    

    In this case it makes sense to specify the workspace property as unique in instance declaration:

    ... Instance (
      entities = Set() +
                 Entity[WorkspaceDocuments]( unique = Set() + Seq("workspace") )
      ...
    )
    

    Variant #2

    case class WorkspaceToDocument
      ( workspace : Workspace, document : Document )
    

    And get documents of a workspace like so:

    Db.query[WorkspaceToDocument]
      .whereEqual("workspace", theWorkspace)
      .whereEqual("document.name", "...") // ability to filter docs
      .fetch()
      .map(_.document)
    

    First variant won't let you filter docs in your query (at least in SORM v0.3.*) but due to ability to set a unique constraint on a workspace it should perform better on workspace-based queries. The second variant is more flexible, allowing you to apply all kinds of filters.

    0 讨论(0)
提交回复
热议问题