I'm building a CakePHP application, and I have a MySQL table which is not related to any controllers/models but I need to insert/update/get data from this table in one of my controllers/models and I want to do it with find function (I know I can write the SQL statement and make ->query in my models but I don't want to do it). The only solutions I saw in the web was to connect models and stuff like that. Any solutions for my case?
Thank you in advance!
A model need not be used by an controller to be a valid model. If you want to operate on the table using model features, then create a model for it or use one on the fly.
You can then use that model from another model via either an association (belongsTo, hasOne). Or, create an instance using ClassRegistry::init('ModelName');
If you do not require the Model to have any associations, and simply want quick access to find records. You can call ClassRegistry::init('ModelName') and CakePHP will auto-create the model for you. (ModelName should be the CamelCase version of the table, see conventions)
Eg: You have a table in your database called documents but do not have a Document.php model file. Calling ClassRegistry::init('Document'); will create a model for that table on the fly.
ClassRegistry::init('Document')->find('all');
or even
$Document = ClassRegistry::init('Document');
$Document->find('all');
In a controller you can also use loadModel() on the fly
$this->loadModel('Document');
$this->Document->find('all');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With