Symfony Doctrine 使用新操作符水合结果

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

是否可以使用 Doctrine 自动构建一个具有子 DTO 作为属性的结果数组?

例如,我们假设只能有一个孩子,并且我有以下实体:

#[Entity]
#[Table(name: 'person')]
readonly class PersonEntity
{
    public function __construct(
        #[Id]
        #[GeneratedValue]
        #[Column(type: Types::INTEGER)]
        public ?int $id = null,
        #[Column(type: Types::STRING, length: 255)]
        public ?string $slug = null,
        #[Column(type: Types::STRING, length: 255)]
        public ?string $firstName = null,
        #[Column(type: Types::STRING, length: 255)]
        public ?string $lastName = null,
        #[Column(type: Types::INTEGER)]
        #[OneToOne(targetEntity: ChildEntity::class)]
        public ?int $childId = null,
    )
    {
    }
}

#[Entity]
#[Table(name: 'child')]
readonly class ChildEntity
{
    public function __construct(
        #[Id]
        #[GeneratedValue]
        #[Column(type: Types::INTEGER)]
        public ?int $id = null,
        #[Column(type: Types::STRING, length: 255)]
        public ?string $slug = null,
        #[Column(type: Types::STRING, length: 255)]
        public ?string $firstName = null,
        #[Column(type: Types::STRING, length: 255)]
        public ?string $lastName = null,
    )
    {
    }
}

现在我想创建一个查询来获取所有人员,并在他们有子集时自动填充子属性:

        $select = 'NEW Person(
            a.id, 
            a.slug, 
            a.firstName, 
            a.lastName, 
            case when c.id IS NULL then NULL else NEW Child(c.id, c.slug, c.firstName, c.lastName)
        )';

        $query = $this->entityManager->createQueryBuilder()
            ->select($select)
            ->from(PersonEntity::class, 'a')
            ->leftJoin(ChildEntity::class, 'c', Join::WITH, 'a.childId = c.id')
            ->getQuery();

目前抛出以下错误:

[Syntax Error] line 0, col 150: Error: Unexpected 'NULL'

有没有办法使用 Doctrine 自动构建这些结果?或者我是否必须使用数组结果数据列表手动水合并构建对象结构?

php symfony doctrine-orm doctrine
1个回答
0
投票

您可以使用 MakerBundle 并让它为您生成实体。这样,建立关系就变得微不足道了。这样您就不需要编写自己的查询。请参阅此处的文档:如何与教义关联/关系合作。如果您想了解我如何仅使用 make 命令设置 iti,这里是一个存储库:stackoverflow-78029639

© www.soinside.com 2019 - 2024. All rights reserved.