many-to-many association -- create, update, delete

24 views
Skip to first unread message

Indy Nagpal

unread,
Nov 19, 2009, 9:07:58 AM11/19/09
to ColdFusion on Wheels
Hi

I'm trying to get my head around associations in CFWheels. Creating a
simple application with posts, categories and post-category-links.

I can read the post-category-link data nicely using the notion of
'shortcuts'.

But I'm struggling to find information on how to create/update/delete
in this scenario.

For example, when I'm creating a post (and assign a couple of
categories to it), how would I add links in the post-category-link
table?

I've looked at the docs and can't seem to find the answer.

Any help would be much appreciated.

Thanks

Indy

Andy Bellenie

unread,
Nov 24, 2009, 11:00:46 AM11/24/09
to ColdFusion on Wheels
You need to create the join records after saving the initial post, so
it's an ideal case for using the afterCreate() callback. I'd do
somethinng like this, although others may have better solutions:

****************
Say your form post looks like this:

params.post.id = 1
params.post.title = 'foo'
params.post.categories = '1,2,3,4

In your model, you set up the following:

<cfcomponent>

<cffunction name="init">
<cfset hasMany(name="post-category-links",shortcut="categories")>
<cfset afterSave(method="assignCategories")>
</cffunction>

<cffunction name="assignCategories">
<cfset var categoryId = 0>
<cfloop list="#this.categories#' index="categoryId">
<cfset model("post-category-links").create
(postId=this.id,categoryId=categoryId)>
</cfloop>
</cfloop>

<cfcomponent>

Finally in your controller all you need to do is save the post with...
<cfset model('post').create(params.post)>

You'll need to add validation and methods to remove unused categories
depending on how you manage it, but this should get you started. The
key is to keep everything in the model.

Per Djurner

unread,
Nov 24, 2009, 10:04:14 PM11/24/09
to cfwh...@googlegroups.com
You have to use the underlying belongsTo / hasMany associations for creating, updating etc.
All the "shortcut" argument does is add one extra method for you to read all the objects for the many-to-many association.


--

You received this message because you are subscribed to the Google Groups "ColdFusion on Wheels" group.
To post to this group, send email to cfwh...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/cfwheels?hl=.



Indy Nagpal

unread,
Nov 26, 2009, 7:15:29 PM11/26/09
to cfwh...@googlegroups.com
Thanks for your responses. I've got it going nicely.

To unsubscribe from this group, send email to cfwheels+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/cfwheels?hl=en.

Reply all
Reply to author
Forward
0 new messages