Welcome Guest, Not a member yet? Register   Sign In
Active Record => What if class variables don't match database table columns?
#1

[eluser]momsenmeister[/eluser]
Hi,

my model classes look like this:

Code:
class User extends Model
{
  var $id = '';
  var $firstname = '';
  var $surname = '';

  function update_entry()
  {
    $this->firstname = $this->input->post('firstname');
    $this->surname = $this->input->post('surname');
    $this->db->where('id', $this->id);
    $this->db->update('user', $this);
  }
}

For updating data I use a function like update_entry().

Like this I can always just use
Code:
$this->user->firstname
in my views, for example.
But my problem is: If my class variables don't exactly match my database table columns, I can't use

Code:
$this->db->update('user', $this);

or I get an exception
Quote:Unknown column in field list.

I try to avoid building a specific array each time I want to update some data.
Is there any way to just ignore columns, that don't exist in my database table?
For example, I might have an extra variable called "initials" in my model to use
Code:
$this->user->initials
in my views, but I might not need an extra column in my database table for it.

Any solution? Any best practices?

Thx!
#2

[eluser]Nick_MyShuitings[/eluser]
IMHO its always best to throw as limited a data set at the DB as is possible. Its also a nice step to trim down your global user array, since in that same step you are validating/filtering.

On the code side, AR takes the array and turns it into an insert or update string, and then tries to run the query. The error message is from the DB which AR then turns back for you. That said, to do what you want you'd need to modify the AR class so that prior to attempting the insert it retrieves the database columns and then filters the array itself. It'd be adding one DB call and then a filtering function.

Perhaps an ORM like datamapper?
#3

[eluser]momsenmeister[/eluser]
Thx Nick!
I try out ORM at the moment, it seems to be exactly what I'm looking for...




Theme © iAndrew 2016 - Forum software by © MyBB