Search code examples
ormcoldfusionrailocfwheels

CFWheels - How do I increment a number in a database column?


Just wondering, with CFWheels ORM, how I go about incrementing a number in a column?

In straight up SQL I would do something like:

UPDATE table 
SET field = field + 1 
WHERE ...

I'd like to avoid "fetching" the value from the column and incrementing it manually. I'll be doing a lot of this in my app, so it's an overhead I could do without (plus I'd also like to keep my code simple and elegant).

Could something like this work?

<cfset post = model("post").findByKey(99) />
<cfset post.update( myColumn = myColumn + 1 ) />

Appreciate some input.


Solution

  • You can abstract this in the base Model.cfc if you need to repeat it a lot:

    <cfcomponent extends="Wheels">
        <cffunction name="incrementColumn" returntype="boolean">
            <cfargument name="key" type="string" required="true">
            <cfargument name="property" type="string" required="true">
    
            <cfset local.record = this.findByKey(arguments.key)>
            <cfset local.record[arguments.property]++>
    
            <cfreturn local.record.update()>
        </cffunction>
    </cfcomponent>
    

    Then you can call it from your controller like so:

    <cfif post = model("post").incrementColumn(params.key, "myColumn")>
        Success
    <cfelse>
        Error
    </cfif>