Schema to support dynamic properties

后端 未结 2 1599
长情又很酷
长情又很酷 2021-01-31 05:26

I\'m working on an editor that enables its users to create \"object\" definitions in real-time. A definition can contain zero or more properties. A property has a name a type. O

2条回答
  •  不要未来只要你来
    2021-01-31 06:13

    You are implementing something called Entity-Attribute-Value model http://en.wikipedia.org/wiki/Entity-attribute-value_model.

    Lots of folks will say it's a bad idea (usually I am one of those) because the answer to your last question, "What would the SQL for fetching..." tends to be "thick hairy and nasty, and gettting worse."

    These criticisms tend to hold once you allow users to start nesting objects inside of other objects, if you do not allow that, the situation will remain manageable.

    For your first question, "what would the "type" column of the prop_defs table hold", everything will be simpler if you have a table of types and descriptions that holds {"numeric","Any Number"}, {"textual","String"}, etc. The first value is the primary key. Then in prop_defs your column "type" is a foreign key to that table and holds values "numeric", "textual", etc. Some will tell you incorrectly to always use integer keys because they JOIN faster, but if you use the values "numeric", "textual" etc. you don't have to JOIN and the fastest JOIN is the one you don't do.

    The query to grab a single value will have a CASE statement:

    SELECT case when pd.type = "numeric" then pv.numeric
                when pd.type = "textual" then pv.textual
                when pd.type = "boolean" then pv.boolean
      from prov_vals pv 
      JOIN prop_defs pd ON pv.prop_def_id = pv.id
     WHERE pv.object_id = 2
       AND pd.name = "Name"
    

提交回复
热议问题