Ave 已经将一些应用程序从 CakePHP 2 重写为 CakePHP 3。我在数据库中有一些结构,列:key(自动生成的键字符串)。在 mysql 中,key 是一个关键字,所以当我写一个 SQL 查询时,我必须将它转义为
INSERT INTO table (`key`) VALUES (....)
不幸的是,当我尝试保存实体时,我收到一个错误:
[42000][1064] You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'key,
该错误在 Cake\ORM\Table 中的 _insert() 方法中触发:
$statement = $this->query()->insert(array_keys($data))
->values($data)
->execute();
任何建议如何避免这种情况? CakePHP 版本 3.5.11
最佳答案
要么重命名列以避免冲突,要么通过 quoteIdentifiers
在数据库连接配置中全局启用 CakePHPs 自动标识符引用。选项:
// in config/app.php
'Datasources' => [
'default' => [
// ...
'quoteIdentifiers' => true,
],
// ...
]
或者仅通过即时切换驱动程序自动引用标志来针对该特定操作:
$driver = $this->getConnection()->getDriver();
$autoQuouting = $driver->isAutoQuotingEnabled();
$driver->enableAutoQuoting(true);
$this->query()/* ... */;
$driver->enableAutoQuoting($autoQuouting);
或者通过手动引用名称并以引用方式传递它:
$connection = $this->getConnection();
$quotedColumnName = $connection->quoteIdentifier($columnName);
// ...
这目前与自动引用兼容,即如果启用自动引用,则引用的名称不会被引用两次,但我不确定这是否真的是一种 promise 的行为!
也可以看看
关于sql - CakePHP 3 + ORM 查询构建器和列名转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48631083/