問題描述
我正在嘗試在 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模板網!