How would you create and store user-defined custom fields in a SQL database?

孤者浪人 提交于 2019-11-30 07:35:35

We add almost in our all application/products additional attribute/field support for given flexibility to user
Like we have a product category, In the category, customer can define additional attribute of any product
what we are doing in the DB level is:
Category Table have some additional column like: Text1Att, Text2Att...for text value support, Num1Att, Num2Att... for Number value support, Date1Att, Date2Att... for datetime value support, ID1Att, ID2Att... support for ID from other table like you can add dropdown, listbox,...
here all the column have String datatype.
what we store here is

we will store meta information here, like for Text1Att meta is
SSN;textbox;50;true;false;Null;
Caption of field;Control Type;Max length;is Required field;is Custom validation required; Custom Validation message;
birth place;textbox;100;true;true;Invalid Value;
Same for Numeric field ...
for date meta information will look like
birth date;Calendar control;true;true;Invalid Date;
Caption of field; Calendar control or can be other;is required;is Custom Validation; Custom Validation message;


What are doing in product table is add same number of column and have datatype text1Att,.. is varchar, num1Att have numeric, date1Att have datetime, ID1Att have int

What we are doing GUI side is : In category definition page add these attribute and build meta information at runtime and store in category table
On the other hand when we define product in category, meta information will be read and traverse from category table and populate in product definition page like other fields.


if u need further help, I can provide you images so that you will better understand how can be done this.
we are experience and analyze, this is much flexible approach

Have a table that stores the field names and types.

field_ID     INT
field_name   VARCHAR
field_type   ENUM('int','float','text','richtext')

Have a table that stores a link to an entry in the record table, a link to an entry in the field table, and the field value.

fieldvalue_fieldID   INT
fieldvalue_recordID  INT
fieldvalue_value     BLOB

Making it searchable is another challenge - you would need to grab any searchable content out of that fieldvalue_value and index that. This would be database-specific. In MySQL you could make that a TEXT value and add a MySQL FULLTEXT index on it.

Your best options are:

  1. Allow the user to alter their own database schema, perhaps by uploading a module or running a script.

  2. Use an XML field, and a database that supports indexes and querying on the contents of that field

These are recommended by Martin Fowler, here: http://martinfowler.com/bliki/UserDefinedField.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!