2

我在找出我从哪里得到这个错误时遇到了一些麻烦:

错误: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'),
)));

现在我读过的大多数东西都会说问题是“姓氏”字段不存在,这正是错误所说的。cake 试图执行的 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 秒后过期。有任何想法吗?

4

2 回答 2

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
于 2013-06-18T07:51:43.230 回答
-1

尝试

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

一个简单的错别字......

于 2013-06-18T00:12:30.117 回答