4

When I try to use a simple Criteria on a property with a different columnname in Many-To-Many-Relation, Doctrine uses the propertyname as the field and not the columnname.

Person ORM Definition

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

Attribute ORM Definition with differing columnname

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

Person::hasAttribute()-Method

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

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

The generated 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` = ?"
Sebus
  • 3,752
  • 3
  • 14
  • 22
  • When I change the criteria to "`key`" it works when Doctrine has to load the relations from the DB, but will result in a PHP-Fatal in my Unit-Tests, because my entity does not have a property "key" or "getKey". – Sebus Oct 25 '17 at 11:35
  • Is your access set to Property on the corresponding class ? By default the access is FIELD? – Alexander Petrov Nov 09 '17 at 14:02
  • What is your Doctrine ORM version? – Jannes Botis Nov 09 '17 at 23:06

1 Answers1

1

The issue is in "lib/Doctrine/ORM/Persisters/Collection/ManyToManyPersister.php" class, in function "loadCriteria()" at lines:

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

the fix was added at github link and the pull request

As you can see, the above code was changed to:

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

Current releases do not use this fix. It will be part of 2.6 release. I suggest you use the code in the master branch.

Update: The fix is available since version 2.6.

Jannes Botis
  • 11,154
  • 3
  • 21
  • 39