Skip to content

Invalid DQL when using selfreferenced entity #1959

@rsemizarov

Description

@rsemizarov

I found the following part of code in EagerLoadingExtension

            } else {
                $queryBuilder->addSelect($associationAlias);
            }

            // Avoid recursion
            if ($mapping['targetEntity'] === $resourceClass) {
                $queryBuilder->addSelect($associationAlias);
                continue;
            }

The problem is that we add the same alias to select for the second time. It confuses Doctrine and can work only occasionally.

The part "Avoid recursion" was added in commit 5ba5180#diff-0e280fa016b79eacb061c504a6348752 with is marked as "Temporary solution". I do not know, what exactly was solved, but it seems very strange.

Below is my code, that is failed because of this.

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * @ORM\Entity()
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="Type", type="string")
 * @ORM\DiscriminatorMap({"C" = "Category"})
 */
abstract class CategoryBase
{
    /**
     * @var int
     *
     * @ORM\Id
     * @Groups({"category"})
     */
    public $id;
}

////////////////

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * Group
 *
 * @ORM\Entity
 * @ApiResource(
 *     attributes={ "normalization_context"= {"groups"={"category"} }}
 * )
 */
class Category extends CategoryBase
{
    /**
     * @var Category[]
     * @ORM\OneToMany(targetEntity="Category", mappedBy="parentCategory")
     * @ORM\JoinColumn(referencedColumnName="parentId")
     * @Groups({"category"})
     */
    public $subcategories;

    /**
     * @var Group
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="subcategories")
     * @ORM\JoinColumn(name="ParentId", referencedColumnName="id")
     */
    public $parentCategory;
}

I tryed to fetch /category/1 , that does not have children and got The discriminator column \"Type\" is missing for \"App\\Entity\\Category\" using the DQL alias \"subcategories_a1\"."
It is long to explain, but the real problem is described above. The generated DQL is

SELECT o, subcategories_a1, subcategories_a1 FROM App\Entity\Category o LEFT JOIN o.subcategories subcategories_a1 WHERE o.id = :id_id

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions