I have been having a hard time wrapping my head around using the relationships OneToMany, ManyToOne and ManyToMany in Transfer so I browsed the Google group for awhile and hacked on a simple example to understand how to take a parent object and add or remove a child and save it.
My Database is:
tblPackage - packages are collections of items and has properties like price
tblItem - stores information on items like quantity
mapItemPackage - has two FKs to the above tables to link them
My Transfer XML is:
...
<manytomany name="items" table="mapItemPackage">
<link to="event.package" column="packageID" />
<link to="event.item" column="itemID" />
<collection type="array">
<order property="itemname" order="asc" />
</collection>
</manytomany>
My simple ColdFusion test:
< !-- normally transfer is instantiated in some other fashion; this is just a hack under MG so you can see getTransfer() -->
<cfset transfer = application["cfusion.war"].framework.getORMService().getTransfer() />
< !-- pull a package from the database that already exists -->
<cfset package = transfer.get("event.package", "42F94767-F68B-CF98-B37F72C20DABFC61") />
< !-- get the items that this package already has -->
<cfset items = package.getItemsArray() />
< !-- display what items this package currently contains -->
Existing Items:<br />
<cfloop from="1" to="#arrayLen(items)#" index="ii">
<cfdump var="#items[ii].getItemName()#" /><br />
</cfloop>
< !-- get the "Helmet" item, which already exists -->
<cfset itm = transfer.get("event.item", "42F94374-D1FF-6FCA-19A2CF17532B7D7C") />
< !-- if it's not already in there, add it -->
<cfif NOT package.containsItems(itm)>
<cfset package.addItems(itm) />
</cfif>
< !-- save the new item to the package -->
<cfset transfer.save(package) />
< !-- verify that the "Helmet" item has been removed -->
<br />Modified Items:<br />
<cfset items = package.getItemsArray() />
<cfloop from="1" to="#arrayLen(items)#" index="ii">
<cfdump var="#items[ii].getItemName()#" /><br />
</cfloop>
< !-- remove helmet from it -->
<cfset package.removeItems(itm) />
<cfset transfer.save(package) />
The output:
Existing Items: Membership fee Commemorative Shirt Saturday Banquet Saturday Lunch Sunday Lunch Modified Items: Membership fee Commemorative Shirt Saturday Banquet Saturday Lunch Sunday Lunch Helmet
Note the “Helmet” is not included in the first list. That’s what I added with addItem().
Pretty neat – Transfer manages the dependency for you; all you do it say “this package should have/not have this item – now save it!” and the rest is done. Not to mention it’s cached and automatically updated for you.
Comments are closed.