How to create custom MySQL queries in CakePHP?

前端 未结 2 427
渐次进展
渐次进展 2020-12-16 05:30

I am trying to create my own MySQL queries in Cakephp.

This is my LocationsController.php:



        
相关标签:
2条回答
  • 2020-12-16 05:56

    The class name of your Location model should be Location, not LocationModel.

    Because of this, CakePHP will generate a 'generic' model for the Locations database table and use that model instead of your own model. Because this generic model does not have a get() method, it will execute get as a SQL statement, causing the error

    Also, inside the Model, you should not use $this->Location->query();, but simply $this->query();

    0 讨论(0)
  • 2020-12-16 06:13

    Location Controller should be:

    <?php
    App::uses('Location', 'Model'); // Y do u need this?
    class LocationsController extends AppController
    {
        public $helpers = array('Html', 'Form');
        function index()
        {
            $this->loadModel("Location");
            $this->LocationModel->getLocations(); // I will strongly discourage using get()
        }
    }
    

    Location Model should be:

    <?php
    App::uses('AppModel', 'Model');
    class LocationModel extends Model {
    
        public $name = 'Location';
    
        public function getLocations() // Try to avoid naming a function as get()
        {
        /** Choose either of 2 lines below **/
    
            return $this->query("SELECT * FROM locations;"); // if table name is `locations`
            return $this->query("SELECT * FROM Location;"); // if table name is `Location` since your public name is `Location`
        }
    }
    
    0 讨论(0)
提交回复
热议问题