教义:加入未按预期工作

问题描述 投票:0回答:1

注意:我将 Doctrine 作为独立项目使用,而不是与 Symfony 框架一起使用。

我有两个具有 OneToMany/ManoToOne 映射的实体。

第一个是产品系列:

#[ORM\Entity]
class Family {
    #[ORM\Id, ORM\Column(type: Types::INTEGER), ORM\GeneratedValue]
    private ?int $id = null;

    #[ORM\Column(type: Types::STRING, length: 50)]
    private string $name;

    /**
     * @var Collection<Subfamily>
     */
    #[ORM\OneToMany(mappedBy: 'family', targetEntity: Subfamily::class)]
    private Collection $subfamilies;

    public function __construct () {
        $this->subfamilies = new ArrayCollection();
    }

    // ...
}

然后是产品子系列:

#[ORM\Entity]
class Subfamily {
    #[ORM\Id, ORM\Column(type: Types::INTEGER), ORM\GeneratedValue]
    private ?int $id = null;

    #[ORM\Column(type: Types::STRING, length: 50)]
    private string $name;

    #[ORM\ManyToOne(targetEntity: Family::class, inversedBy: 'subfamilies'), ORM\JoinColumn(nullable: false)]
    private Family $family;

    // ...
}

现在我想获取家庭列表(如果可能的话,仅获取

Family->subfamiles
属性中的匹配子家庭),其中 subfamily 名称以“-1”结尾。 我尝试编写以下查询:

$query = $this->entityManager->createQuery(<<<'DQL'
SELECT f, s
FROM Tests\Entities\Entities\Family f
JOIN Tests\Entities\Entities\Subfamily s
WHERE s.name LIKE '%-1'
DQL
);

$families = $query->getResult();
foreach ($families as $family) {
    echo get_class($family) . ' : ' . ($family instanceof Family ? $family->getName() : '') . PHP_EOL;
}

但我没有得到预期的结果。它返回给我所有家庭(即使他们根本没有子家庭)和不同实体中的匹配子家庭:

Tests\Entities\Entities\Family : Famille 1
Tests\Entities\Entities\Subfamily : 
Tests\Entities\Entities\Family : Famille 2
Tests\Entities\Entities\Family : Famille 3
Tests\Entities\Entities\Subfamily : 
Tests\Entities\Entities\Subfamily : 

如果我检查 Doctrine 使用的 Mysql 查询,JOIN 没有 ON 条件:

SELECT f0_.id AS id_0, f0_.name AS name_1, s1_.id AS id_2, s1_.name AS name_3, s1_.family_id AS family_id_4
FROM Family f0_ 
  INNER JOIN Subfamily s1_ 
WHERE s1_.name LIKE '%-1'

但是根据文档和周围找到的所有示例,我不需要在查询中显式使用WITH

php doctrine
1个回答
0
投票

您的加入错误:

更改:JOIN Tests\Entities\Entities\Subfamily s 至:加入 f.subfamilies s

结果:

$query = $this->entityManager->createQuery(<<<'DQL'
SELECT f, s
FROM Tests\Entities\Entities\Family f
JOIN f.subfamilies s
WHERE s.name LIKE '%-1'
DQL
);
© www.soinside.com 2019 - 2024. All rights reserved.