CF9 ORM Quick Tip - Removing All Items from A Collection
Posted At : October 13, 2009 2:48 PM | Posted By : Bob Silverberg
Related Categories: OO Design, ColdFusion, CF ORM Integration
For this example of using ColdFusion 9's ORM features, let's assume we have a User object and a Department object. The Department has a collection of Users, like so:
2 property name="DeptId" fieldtype="id" generator="native";
3 property name="Name";
4 property name="Users" fieldtype="one-to-many" type="array"
5 cfc="User" fkcolumn="DeptId" singularname="User";
6}
Let's also say that Department 1 currently has 3 Users assigned to it, call them User1, User2 and User3. Now, we want to write some code that will empty the Department's collection of Users. A first attempt might look something like:
2for (i = 1; i LTE ArrayLen(Users); i = i + 1) {
3 Department.removeUser(Users[i]);
4}
But this won't work. In fact, if you run that code you'll see that you end up with a Department that still has User2 assigned to it. The reason this happens is that as soon as you remove User1 from the collection, the array shrinks, so User2 now occupies position 1 and User3 occupies position 2. So the next time through the loop, User3 gets removed (because i now equals 2) and Users[2] is User3. Then the loop finishes because the condition is met.