CakePHP 3 + ORM查询构建器和列名称转义

时间:2018-02-05 20:39:19

标签: sql cakephp cakephp-3.x quoting reserved-words

已经将CakePHP 2中的某些应用程序重写为CakePHP 3.我在数据库中有一些结构,其中包含column:key(自动生成的键 - 字符串)。在mysql中key是一个关键字,所以当我编写SQL Query时,我必须将其作为

进行转义
subprocess.call(["aws", "ec2", "describe-instances", "--instance-ids", '"{}"'.format(instanceid)])

不幸的是,当我尝试保存实体时,我收到错误:

INSERT INTO table (`key`) VALUES (....)

该地方的_insert()方法中的Cake \ ORM \ Table中触发了该错误:

[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, 

有任何建议如何避免这种情况? CakePHP版本3.5.11

1 个答案:

答案 0 :(得分:0)

通过quoteIdentifiers选项重命名列以避免冲突,或者在数据库连接配置中全局启用CakePHP自动标识符引用:

// 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);
// ...

目前这与自动引用兼容,即如果启用自动启动,引用的名称将不会被引用两次,但我不确定这是否实际上是承诺的行为!

另见