Welcome Guest, Not a member yet? Register   Sign In
Creating custom/calculated model properties
#1

[eluser]optimal[/eluser]
Hello,

I'm looking for some advice on best practices for representing a calculated or custom property of a model in CI. I've checked the docs, forum archives, and BambooInvoice but only found straight database calls in the models and no additional or computed values.

For example, if I wanted to add a mathematical "difference" value to each row of my query result set (based on the difference between two columns), and then expose this value as a model property, how would I best accomplish this?

Put another way, if I'm going to call my "get_all" function and return the query results to my controller, what's the best way to pop some additional values in there?

Two options that won't work for me in this case are denormalizing the database by adding a calculated column (and thus creating database redundancy), or using DBMS-specific functions (creating platform dependencies or at minimum the need to ensure there aren't any!).

Thank you!
#2

[eluser]kgill[/eluser]
My thoughts:

I know it was just an example but for something simple I'd let the DB engine take care of it and do it via the query itself:

select x, y, z, x - y difference
from foo

As long as it's using standard SQL (sum, avg, count, basic math, etc) use the DB as much as possible, if you need to do more complex calculations that will delve into the realms of DB specific functions and you must avoid tying yourself to a specific DB, you're going to have to do it in code.

It's perfectly fine do that in your model - either use PHP's array functions to manipulate the result set or iterate through it and build an array to return to the controller. Models are there to represent something you're working with and while the majority of the time that's going to involve database columns - if a calculated field is needed that's the most logical place for it.

- K
#3

[eluser]optimal[/eluser]
Hey kgill,

Thanks for your response. I thought there might be a different way to handle this, but I guess I should just manipulate the array as you suggested.

I like CI because it seems to offer enough functionality to be worthwhile, but not so much that I'm no longer the captain of the ship. Wink




Theme © iAndrew 2016 - Forum software by © MyBB