Search code examples
coldfusioncoldfusion-9

How do I to map a foreign key column referring two tables?


In ColdFusion using ORM, how do I to map a foreign key column referring two tables?

My example.

At the moment an Image can belong to either a human or alien

Image.cfc
property name="imageID" fieldtype="id" generator="guid";

// Related Object Properties (many-to-one)
property name="Human" fieldtype="many-to-one" fkcolumn="HumanID" cfc="human";
property name="Alien" fieldtype="many-to-one" fkcolumn="AlienID" cfc="alien";

This leaves me with a table looking like this..

Image.cfc

    ID   NAME    HumanID  AlienID
    1    img1    10       NULL
    2    img2    NUll     8

To me NULLs smells bad!

So can I replace this with one mapping for both objects? Or If I create a category table? Any Ideas?

Thanks

Spark


Solution

  • You can't map a single property to more than one parent object. So you have two options here.

    You will need to map this as a class per heirarchy where you will have classes for HumanImage and AlienImage that extend the base Image class

    // Image.cfc
    component persistent="true" {
        property name="id" generator="guid";
        property name="name";   
    }
    
    // AlienImage.cfc & HumanImage.cfc
    component persistent="true" extends="Image" joincolumn="id" {
    }
    
    // Alien.cfc
    component persistent="true"  {
        property name="id" generator="guid";
        property name="Image" fieldtype="one-to-many" cfc="AlienImage"
          fkcolumn="fkAlienID";
    }
    
    // Human.cfc
    component persistent="true"  {
        property name="id" generator="guid";
        property name="Image" fieldtype="one-to-many" cfc="HumanImage"
          fkcolumn="fkHumanID";
    }