cakePHP: Can you query the database from a helper class?
-
26-09-2019 - |
문제
Hi just need to know whether you can query the database from inside a helper class, whether you should and how you do it.
Thanks
해결책
You could, by passing a reference to the Model into the View as a variable via $this->set() and then querying it...but you shouldn't. It's messy ;-)
CakePHP uses the MVC model, and helpers are part of the View (the V of MVC) - their job is purely to display the (already available) information passed to it from the controller.
If your view needs extra information , then your controller should have already queried the Models to get it.
I'd suggest you read up on the MVC model if you're not familiar with it, then some refactoring might be in order!
다른 팁
Yes. You can query the database from your helper file. Please check this :-
class YourHelperNameHelper extends AppHelper {
function queryDbFromHelper()
{
// Load your model here
App::import('Model','ModelName');
$this->ModelName = new ModelName();
//now you can use find method or another method to query DB.
return $this->ModelName->find('all');
}
}
// Include this helper in controller
var $helpers = array('YourHelperName');
// call this function in helper file.
$this->YourHelperName->queryDbFromHelper();