How to create custom MySQL queries in CakePHP?(如何在 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 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 CakePHP 中创建自定义 MySQL 查询?
基础教程推荐
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- php中的foreach复选框POST 2021-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- php中的PDF导出 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- 将变量从树枝传递给 js 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
