Search code examples
coldfusioncoldfusion-8

Grouping Custom Attributes in a Query


I have an application that allows for "contacts" to be made completely customized. My method of doing that is letting the administrator setup all of the fields allowed for the contact. My database is as follows:

Contacts

  • id
  • active
  • lastactive
  • created_on

Fields

  • id
  • label

FieldValues

  • id
  • fieldid
  • contactid
  • response

So the contact table only tells whether they are active and their identifier; the fields tables only holds the label of the field and identifier, and the fieldvalues table is what actually holds the data for contacts (name, address, etc.)

So this setup has worked just fine for me up until now. The client would like to be able to pull a cumulative report, but say state of all the contacts in a certain city. Effectively the data would have to look like the following

California (from fields table)

  • Costa Mesa - (from fields table) 5 - (counted in fieldvalues table)
  • Newport 2

Connecticut

  • Wallingford 2
  • Clinton 2
  • Berlin 5

The state field might be id 6 and the city field might be id 4. I don't know if I have just been looking at this code way to long to figure it out or what,

The SQL to create those three tables can be found at https://s3.amazonaws.com/davejlong/Contact.sql


Solution

  • You've got an Entity Attribute Value (EAV) model. Use the field and fieldvalue tables for searching only - the WHERE caluse. Then make life easier by keeping the full entity's data in a CLOB off the main table (e.g. Contacts.data) in a serialized format (WDDX is good for this). Read the data column out, deserialize, and work with on the server side. This is much easier than the myriad of joins you'd need to do otherwise to reproduce the fully hydrated entity from an EAV setup.