Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

php - How to create custom MySQL queries in CakePHP?

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

This is my LocationsController.php:

<?php
App::uses('Location', 'Model');
class LocationsController extends AppController
{
    public $helpers = array('Html', 'Form');
    function index()
    {
        $this->loadModel("Location");
        $this->Location->get();
    }
}

This is my LocationModel.php:

<?php
App::uses('AppModel', 'Model');
class LocationModel extends Model {

    public $name = 'Location';

    public function get()
    {
        $this->Location->query("SELECT * FROM locations;");
    }
}

As you can see, I am just trying to perform a simple query but it doesn't work. I get this error:

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error 
in your SQL syntax; check the manual that corresponds to your MySQL server 
version for the right syntax to use near 'get' at line 1

When I use one of the magic methods like find("all") instead, it works...

Can you see what the problem is? I really can't and I'm only trying to do a simple task!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...