Search code examples
coldfusioncoldfusion-9

cf9 ORM Computed Column - Can it call a method, or include general cfml logic as opposed to SQL


My Persistant model has a 'status' field, which can be 0 or 1.

I have a method in my model called getStatusLabel(), which returns "Active" or "Retired", depending on what status is passed to it.

public function getStatusLabel(required status){
        if (status eq 1)
            return "Active";
        else if (status eq 0)
            return "Retired";
    }

I was thinking it would be great if this could be setup as a computed column, but can't quite think how to do this. All computed column examples have a SQL Statement as the formula.

Is it possible to call this (or another) method as my formula (making it easier to access via my model), or does the formula need to be a SQL statement?

Alternatively, is is possible to include the logic of the method straight in as the 'formula'.

When I attempt either, I am getting error: Could not initialize collection so guessing this can't be done, but would be brilliant if it could, so worth asking.

Many Thanks in advance!

Jason


Solution

  • If you're using a computed column in SQL Server, you can set the column definition to this:

    CASE WHEN status = 1 THEN 'Active' ELSE 'Retired' END
    

    Set the column to persisted so it doesn't have to be calculated with each query, and you should then be able to use that in your ORM. Just make sure it's marked as not updatable or insertable.

    Also, you can have the getStatusLabel method use the status property of the object without passing it in as an argument:

    public function getStatusLabel(){
        if (this.status eq 1)
            return "Active";
        else if (this.status eq 0)
            return "Retired";
    }
    

    If you use that function, just referencing the local status property, does that work as you'd expect?