开发者

What's the best way of clearing a list so I can re-add the elements for ColdFusion 9 ORM?

Let's say I have a Store and a Product entity, with a many-to-many relationship between them, and both are persistent CFC's.

I want to update an existing Store's products using a list of product IDs from a form POST, which means that I have to first remove all the products. What's the best way of doing this? So far I've tried using ArrayNew(1):

<cfscript>
    store = entityLoadByPK("Store", FORM.id);

    // clear the products by assigning it to a new array
    store.setProducts(ArrayNew(1));

    // re-add the products
    for (id in productid)
    {
        product = entityLoad("Product", id);
        store.addProduct(product);
    }

    entitySave(store);
</cfscript>

And I've tried to remove the products using a loop:

<cfscript>
    store = entityLoadByPK("Store", FORM.id);

    // clear the products by remo开发者_开发问答ving them with a loop
    for (product in store.getProducts())
    {
        store.removeProduct(product);
    }

    // re-add the products
    for (id in productid)
    {
        product = entityLoad("Product", id);
        store.addProduct(product);
    }

    entitySave(store);
</cfscript>

Both work fine, but is there a better way of handling this? Or does it not matter and both will do the same thing behind the scenes (namely in the SQL)?


Add these functions in store.cfc. Optionally, check if variables.products exists first.

void function clearProducts()
{
    arrayClear(variables.products);
}

void function addProducts(required Array ps)
{
    for (var p in ps)
        ArrayAppend(variables.products, p);
}

Then in Controller layer

var hql = "from Product where id in (:productIDs)";
var products = ormExecuteQuery(hql, {productIDs=Form.productID});

if (!store.hasProduct())
    store.setProducts(products);
else
{
    store.clearProducts();
    store.addProducts(products);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜