如何在 CakePHP 中创建自定义 MySQL 查询?

时间:2023-03-20
本文介绍了如何在 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!

推荐答案

Location 模型的类名应该是 Location,而不是 LocationModel.

The class name of your Location model should be Location, not 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 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:为belongsToMany CakePHP 3 进行分页的条件 下一篇:如何使用 PHPDoc 表示法声明局部变量的类型?

相关文章

最新文章