如何在CakePHP中创建自定义MySQL查询? [英] How to create custom MySQL queries in CakePHP?

查看:93
本文介绍了如何在CakePHP中创建自定义MySQL查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Cakephp中创建自己的MySQL查询。

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

这是我的 LocationsController.php

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

这是我的 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

当我使用像find(all)这样的魔法时,它会工作...

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!

推荐答案

位置,而不是 LocationModel

,CakePHP将为Locations数据库表生成一个通用模型,并使用该模型而不是您自己的模型。因为这个通用模型不有 get()方法,它将执行 get 作为SQL语句,导致错误

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

此外,在模型中,不应使用 $ this-> Location-> query ); ,但只是 $ this-> query();

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

这篇关于如何在CakePHP中创建自定义MySQL查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆