【问题标题】:Avoid Doctrine to return full related entity避免 Doctrine 返回完整的相关实体
【发布时间】:2021-05-17 07:11:49
【问题描述】:

我是 Symfony 的新手,我正在尝试从我的内容表中获取所有记录。它有效,但它也返回相关实体的所有字段。

$content = $this->contentRepository->findAll();

这是我得到的:

[{
    "id": 2,
    "field1": "xx",
    "field2": "xx",
    "field3": 22,
    "field4": {"id":1, "field1":"xx", ...},
    ....
},...]

在 field4 上,我只想获取 id 作为值,而不是整个对象。就像我在做 SQL 一样。 从其他地方阅读我发现有关lazy_loading 的信息,但它似乎不起作用。

【问题讨论】:

标签: php sql symfony doctrine


【解决方案1】:
public function getContentData(): array
{
    $qb = $this->createQueryBuilder('c');

    $qb->select('c.id as id, IDENTITY(c.field4) as field4, c.field1 as field1, c.field2 as field2, c.field3 as field3');

    return  $qb->getQuery()->getArrayResult();
}

但是如果要获取字段数组,最好是获取实体数组并通过JMSSerializerBundleThe Serializer Component进行序列化

【讨论】:

    【解决方案2】:

    只需转到您的 contentRepository 文件并定义这样的函数

    public function getAllContentIds()
    {
        $qb = $this->createQueryBuilder();
        return $qb->select('id')
            ->from('YourBundleName:YourTableName')
            ->getQuery()
            ->getResult();
    }
    

    然后像这样使用这个函数

    $contentIds = $this->contentRepository->getAllContentIds();
    

    【讨论】:

    • 我的意思是,学说返回整个关联实体作为field4的值,我只需要那个实体的id。
    • 其他字段没问题
    • 考虑更新您的答案以匹配问题。这可能会很有挑战性,因为 Doctrine 不支持加入部分实体。
    猜你喜欢
    • 1970-01-01
    • 2021-11-08
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    相关资源
    最近更新 更多