Saturday, October 20, 2012

Coldfusion ORM many-to-many on same entity

Well, there is a new job, as of 08/01/2012 and new excitement. Also new problems to solve and code. Worked on creating ColdFusion 9 ORM settings for many-to-many relationship to the same entity. Here is a result:
<cfscript>
component output="false" persistent="true" table="Person" {
property name="personid" column="personid" generator="identity" index="true" fieldtype="id" ormtype="int" insert="false" update="false";
property type="timestamp" name="created" generated="insert";
property name="name" ormtype="string";
property
name="guides"
singularname="guide"
fieldtype="many-to-many"
CFC="Person"
linktable="PersonToPerson"
lazy="true"
cascade="all"
orderby="name"
inverse="true";
property
name="followers"
singularname="follower"
fieldtype="many-to-many"
CFC="Person"
linktable="PersonToPerson"
lazy="true"
cascade="all"
orderby="name";
function init() {
variables.followers = [];
variables.guides = [];
}
public void function addGuide(required Person guide) {
if (not hasguide(arguments.guide)) {
// set this side
arrayAppend(variables.guides,arguments.guide);
// set the other side
arrayAppend(arguments.guide.getFollowers(),this);
}
}
public void function removeGuide(required Person guide) {
if (hasguide(arguments.guide)) {
// set this side
var index = arrayFind(variables.guides,arguments.guide);
if (index gt 0) {
arrayDeleteAt(variables.guides,index);
}
// set the other side
index = arrayFind(arguments.guide.getFollowers(),this);
if (index gt 0) {
arrayDeleteAt(arguments.guide.getFollowers(),index);
}
}
}
public void function addFollower(required Person follower) {
arguments.follower.addGuide(this);
}
public void function removeFollower(required Person follower) {
arguments.follower.removeGuide(this);
}
}
</cfscript>
view raw Person.cfc hosted with ❤ by GitHub
I used some of the code from Bob Silverbergs blog here. Thanks Bob.

No comments: