【问题标题】:Adding new columns to table dynamically for custom fields为自定义字段动态添加新列到表中
【发布时间】:2012-06-15 09:20:09
【问题描述】:

我正在为我的应用程序构建自定义字段功能。这允许管理员根据站点的需要添加自定义配置文件字段供用户填写。

架构很简单

field_meta (store some metadata about the field)
================================================
id
type //type of field
field_name //name of the field in the fields table
render_data //Some data to use when rendering the form field

field
===================
id
name //Default field that can't be deleted
address //Default field that can't be deleted
customfield_1
customfield_2

field_meta 表用于存储字段的一些元数据,以便我们渲染表单字段。

然后将每个字段存储在field 表的一个新列中。

问题: 为了可用性和不必处理用户选择保留字或使用非英语单词作为列名,我不会要求用户为列名选择名称。

我目前正在考虑按字段类型调用列名(应用程序中有很多类型(电子邮件、网站、文本、段落文本等),仅举几例)并添加一个数字。一些例子:

  • Email_1
  • Text_1
  • Text_2
  • Text_3
  • Email_2

但是,这种方法的问题在于它需要大量的工作才能得出列名。我需要获取所有列,选择与我正在创建的列类型相同的列,解析最大的数字,然后创建列。

有没有更好的策略来做到这一点?或者也许是一种完全不同的方式来命名消除这些问题的列?

【问题讨论】:

    标签: mysql


    【解决方案1】:

    不要尝试动态添加列,这是一种缓慢(而且形式不佳)的方法。

    相反,将额外的列存储在一个新表中,每个都有自己的 ID。然后有另一个表来存储用户 ID、额外的列 ID 和该用户的属性信息。这将模拟添加新列,而实际上不必这样做。

    编辑: 事实上,它听起来确实像 EAV。架构:
    属性{id:int, name:string}
    用户{id:int, name:string,(任何其他需要...)}
    Users_attributes{Attribute_id:int, User_id:int, Attribute_info:string}

    然后只需将任何新属性输入到 Attributes(ID 递增)中,并将任何新用户信息输入到 User_attributes 中,并带有适当的 User_id 和 Attribute_id。

    【讨论】:

    • 您能为此提供一个示例架构吗?这听起来有点像 EAV。
    【解决方案2】:

    我决定采用我原来的方法,即基本上创建一个由类型和递增数字组成的列名:

    • Email_1
    • Text_1
    • Text_2
    • Text_3

    虽然生成名称需要付出相当大的努力,但这仅在创建配置文件字段时完成,因此性能影响只会在此期间发生。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多