[eluser]eggshape[/eluser]
Hi,
I load and use multiple models in an app I recently built. I can not show you the exact code (not allowed), but I can explain how I did it. Here is something similar:
Code:
class Root_Controller extends Controller {
//every controller extends Root_Controller and inherits and overwrites these properties
protected $models = array(); // load models here
//The following is called in the constructor or save function of each controller to autoload the models
protected function set_models()
{
$models = $this->models;
if (count($models) > 0)
{
while ($model = array_shift($models))
{
$this->load->model($model);
}
}
}
// This function is called on form submission to save data to all the relevant models
protected function save_form()
{
$validate = $this->set_all_validation();
if ($validate and $this->validation->run() === false)
{
return 1;
}
$models = $this->models;
while ($model = array_shift($models))
{
if (! $this->$model->save())
{
log_message('error', 'Could not save model data');
return 1;
}
}
return 0;
}
}
As you may have noted that all the models share a save() function; you can copy this into every model, but I chose to add/replace the default Model class, so all my models inherit the same function. So in your Model class or model classes, you can then retrieve the field names appropriate to each model and save to the database.
Code:
class Model {
// table name
protected $table = '';
// array to hold data for each model
protected $data = array();
// I do something like this:
// This retrieves existing data;
protected function init_data()
{
$this->db->where(array('id' => $id));
$query = $this->db->get($this->table);
if ($query->num_rows() === 1)
{
$this->data = $query->row_array();
}
}
// this function sets the keys for the data array using table field names
protected function set_fields()
{
$this->data = array();
// uses CI DB utility function
$fields = $this->db->list_fields($this->table);
// set keys to field names
while ($field = array_shift($fields))
{
$this->data[$field] = '';
}
}
// And in the save function you would iterate the $data array and assign any new
// $_POST data to the keys
protected function save()
{
foreach ($this->data as $field => $value)
{
if (isset($_POST[$field]))
{
$this->data[$field] = $this->input->post($field);
}
}
}
}
I hope this gives you enough clues to implement your own version.