A little gotcha with foreign key names

Someone posted a very interesting problem in Slack today and so I thought I'd write about it as the solution may help someone else. The problem relates to naming a foreign key field using the same name as the object it lives in...

The setup

A preside object, "video", with the following simple definition:

/**
 * video.cfc
 */
component {
   property name="slug" type="string" required=true;
   property name="video" relatedto="asset" relationship="many-to-one" required=true; // note same name as this cfc 
}

The error

An error occurs here, "key [slug] doesn't exist" when doing something like this:

selectData(
      objectName = "video"
    , filter     = { slug="something" }
);

What?!

The solution

The solution here is to rename the "video" property. Having a foreign key field with the same name of the object it lives in is confusing for Preside but also for other developers. In this case, "asset", or "video_asset" would be a clearer choice.

While this could be seen as a bug (and is), the reality is that naming a foreign key the same name as the object it lives in will lead to scenarios where Preside cannot decide which object it needs to use. If you were to select "video.label", for example - do you mean the "label" field on the video object, or the "label" field on the "video" property's related object?!