doctrine-orm – 带有Criteria和Many-To-Many-Relation的查询中的错误字段名

当我尝试在Many-To-Many-Relation中具有不同列名的属性上使用简单Criteria时,Doctrine使用propertyname作为字段而不是columnname.

人ORM定义

...
manyToMany:
    attributes:
        targetEntity: Attributes
        cascade: ['persist']
        joinTable:
            name: person_attribute
            joinColumns:
                person_id:
                    referencedColumnName: id
            inverseJoinColumns:
                attribute_id:
                    referencedColumnName: id
...

具有不同列名的属性ORM定义

...
name:
    type: string
    nullable: false
    length: 50
    options:
        fixed: false
    column: '`key`'
...

人:: hasAttribute() – 方法

$criteria = Criteria::create()
    ->where(Criteria::expr()->eq('name', $attributeName))
    ->setFirstResult(0)
    ->setMaxResults(1);

if ($this->getAttributes()->matching($criteria)->first()) {
    return true;
}

生成的Statement

SELECT 
    te.id AS id, 
    te.description AS description, 
    te.key AS key 
FROM 
    attribute te 
JOIN 
    person_attribute t 
ON 
    t.attribute_id = te.id 
WHERE 
    t.person_id = ? 
        AND 
    te.name = ?     ## <- This should be "te.`key` = ?"

最佳答案 问题出在“lib / Doctrine / ORM / Persisters / Collection / ManyToManyPersister.php”类中,在函数“loadCriteria()”中的行:

foreach ($parameters as $parameter) {
        list($name, $value) = $parameter;
        $whereClauses[]     = sprintf('te.%s = ?', $name);
        $params[]           = $value;
}

修复程序在github linkpull request添加

如您所见,上面的代码更改为:

foreach ($parameters as $parameter) {
        list($name, $value) = $parameter;
        $field = $this->quoteStrategy->getColumnName($name, $targetClass, $this->platform);
        $whereClauses[]     = sprintf('te.%s = ?', $field);
        $params[]           = $value;
}

当前版本不使用此修复程序.
它将成为2.6版本的一部分.
我建议你使用master分支中的代码.

点赞