The query () function of the model is sometimes very useful, and it can execute SQL statements wherever the data is needed.
But not where the query () method is invoked is appropriate. In particular, invoking the model's query () method directly in the controller
$this->mymodel->query (' Here comes the SQL statement ');
Calling the model's query method in the controller is not possible, but it introduces database-related code, which violates the principles of the MVC pattern
A cleaner solution is to move the SQL statements into the model, so the code above is refactored to:
In the model
function dosomething () {
$this->query (' Here comes the SQL statement ');
}
I in the controller
$this->mymodel->dosomething ();
Do not include database-related code in the controller, the code should be placed in the model, there are models to deal with
This scenario requires more code to be written, but it brings some advantages:
* Easy to test
* More readable
* Avoids the query code export replication between multiple controllers, making the code more concise
CakePHP's Query method, directly written in the controller is not a bit inappropriate