CodeIgniter Forums
Model and Active Record with private properties. - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Model-View-Controller (https://forum.codeigniter.com/forumdisplay.php?fid=10)
+--- Thread: Model and Active Record with private properties. (/showthread.php?tid=61582)



Model and Active Record with private properties. - rafaelwendel - 04-27-2015

Hi there,

I am developing a model to insert a record in the database. I am using private property and see that the "insert" the object "db" generates the error "You must use the" set "method to update an entry". My question is: I can not use private property and protected in my model? Only public?

Thanks!

Rafael Wendel Pinheiro
Capivari/BR;


RE: Model and Active Record with private properties. - Avenirer - 04-27-2015

I don't understand what does set() method have to do with private and protected properties. Could you show us the model?


RE: Model and Active Record with private properties. - mwhitney - 04-28-2015

Since you mentioned Active Record, I'm assuming you're using CI 2 instead of CI 3.

In your model, $this->db refers to CI's database library, so, if you wanted to insert something using CI's Active Record methods, you would use
Code:
$this->db->insert('table_name', $data);

http://www.codeigniter.com/userguide2/database/active_record.html#insert

$data can be an object or an array, but, if it's an object, the object must have a set of public properties which match the column names in your database (if it's an array, the keys in the array would match the column names in the database).

The message you are alluding to, though, implies you are performing an update via
Code:
$this->db->update('table_name', $data);

http://www.codeigniter.com/userguide2/database/active_record.html#update

Whether performing an insert or an update, you can either supply the $data to the insert()/update() method, or use the set() method to set individual columns:
Code:
$this->db->set('column_name', $value);

(The set() method is documented on the same page as the insert() and update() methods, just scroll up from update() or scroll down from insert().)

In any case, all properties and methods defined within your model are available to any other method in your model. The access modifiers (public/protected/private) only define whether other classes can access those properties/methods.

http://php.net/manual/en/language.oop5.visibility.php


RE: Model and Active Record with private properties. - rafaelwendel - 04-28-2015

mwhitney,

First, thank you for your help. I'm using CI 3 and had this doubt. But now I think I did.

Thanks again.

Rafael Wendel Pinheiro
Capivari/BR;


RE: Model and Active Record with private properties. - mwhitney - 04-29-2015

CI 3 would change the links, and it's called Query Builder instead of Active Record, but the basic use of $this->db is the same.