CakePHP:未找到列:1054未知列

时间:2013-06-17 23:37:49

标签: cakephp cakephp-2.3

我在查找我从哪里收到此错误时遇到了一些问题:

错误:SQLSTATE [42S22]:找不到列:1054'字段列表'中的未知列'HomeVisitorDemographic.Last Name'

首先$this->set('homeVisitor', $this->HomeVisitorDemographic->find('list'));工作正常。

当我尝试运行时会出现问题:

$this->set('homeVisitor', $this->HomeVisitorDemographic->find('list', array(
    'fields' => array('id','Last Name'),
)));

现在我读过的大多数内容都会说问题是“姓氏”字段不存在,这正是错误所说的。蛋糕试图执行的SQL如下:

SQL Query: SELECT `HomeVisitorDemographic`.`id`, `HomeVisitorDemographic.Last Name`
    FROM `cake`.`HomeVisitorDemographics` AS `HomeVisitorDemographic` WHERE 1 = 1

从我的数据库:

mysql> describe HomeVisitorDemographics;
+------------------+--------------+------+-----+---------+----------------+
| Field            | Type         | Null | Key | Default | Extra          |
+------------------+--------------+------+-----+---------+----------------+
| id               | int(11)      | NO   | PRI | NULL    | auto_increment |
| Last Name        | varchar(70)  | NO   |     | NULL    |                |
| First Name       | varchar(70)  | NO   |     | NULL    |                |
+------------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql>

所以,我真的有点困惑,为什么我无法拉开场地。也许我只是累了,忽略了一些简单的事情?我可以看到那个领域确实存在。它确实从网站上的其他页面拉出姓氏,所以我知道它存在并且数据在那里。我的调试级别设置为2,因此缓存应在10秒后过期。 有什么想法吗?

2 个答案:

答案 0 :(得分:4)

带空格的字段名......

有问题。如果仔细查看正在生成的sql:

SELECT 
    `HomeVisitorDemographic`.`id`, 
    `HomeVisitorDemographic.Last Name`,
FROM
    `cake`.`HomeVisitorDemographics` AS `HomeVisitorDemographic`
WHERE 
    1 = 1

生成的查询正在查找名为HomeVisitorDemographic.Last Name字段,同样如错误消息中所示(尽管在错误消息中,很容易将其作为table.field错误地读取)。

此方案中的“最佳”解决方案是将字段重命名为更合理的字段 - 例如“last_name”。

转义值不会再次转义

如果无法更改架构,另一种解决方案是自行转义字段名:

$this->HomeVisitorDemographic->find('list', array(
    'fields' => array(
        'id',
        '`HomeVisitorDemographic`.`Last Name`' # <- note backticks
    )
));

应该生成查询:

SELECT 
    `HomeVisitorDemographic`.`id`, 
    `HomeVisitorDemographic`.`Last Name`,
FROM
    `cake`.`HomeVisitorDemographics` AS `HomeVisitorDemographic`
WHERE 
    1 = 1

答案 1 :(得分:-1)

尝试

... 'fields' => array('id' => 'Last Name'),

一个简单的错误....