Welcome Guest, Not a member yet? Register   Sign In
Models and Virtual Database Fields
#3

[eluser]kaejiavo[/eluser]
Hi Shaun,

this depends on the functions you are performing in your model.
Two szenarios for example:

You use your model mainly to retrieve only one record:
Code:
class my_model extends Model
{

   public $expenses;
   public $date;
   ...


   __construct()
   {
     parent::__construct();
   }

   function get_budget()
   {
    // retrieve budget from database and fill variables
    $this->monthly_amount = ...

    // calculate virtual fields and set the variables
    $this->$expenses = _get_expenses();

    
   }

   function _get_expenses()
   {
    // calculate your "virtual" Field
    $expenses = ....
    return $expenses;
   }
}

// in your controller you then can use it:

$this->my_model->$expenses;
(of course there are many different ways to do this w/ private vars and setters/getters and so on - really depends on your context...)

If you need the fields calculated for many records you better calculate the fields in the SQL Query with aliases you want to use as field names and there you go.
Code:
$query = $this->db->query('SELECT *, (Your calculation) as expenses, ... FROM budgets WHERE ...');

foreach ($query->result() as $row)
{
   echo $row->id;
   echo $row->name;
   echo $row->monthly_amount;
   // 'virtual' fields (calculated)
   echo $row->expenses;
   ...
}

Marco


Messages In This Thread
Models and Virtual Database Fields - by El Forum - 10-26-2010, 02:55 PM
Models and Virtual Database Fields - by El Forum - 10-26-2010, 04:01 PM
Models and Virtual Database Fields - by El Forum - 10-27-2010, 03:20 AM
Models and Virtual Database Fields - by El Forum - 10-27-2010, 10:00 AM
Models and Virtual Database Fields - by El Forum - 10-27-2010, 10:09 AM
Models and Virtual Database Fields - by El Forum - 10-27-2010, 10:26 AM



Theme © iAndrew 2016 - Forum software by © MyBB