Domanda

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.

È stato utile?

Soluzione

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>

Altri suggerimenti

the orm in cfwheels doesn't support this. for stuff like that straight sql is the way to go. the best thing to do is to create a custom method on you model to encapsulate the logic.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top