简体   繁体   中英

Avoid Doctrine to return full related entity

I am new in Symfony and I am trying to get all the records from my content table. It works but it also returns all the fields from the related entity.

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

And here is what I get:

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

On field4 I would like to get only the id as a value, instead of the whole object. Like if I were doing a SQL. Reading from other places I found about lazy_loading but it doesn't seem to work.

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();
}

But if you want to get an array of fields, it will be better to get the array of entities and serialize them by JMSSerializerBundle or The Serializer Component

Just go to your contentRepository file and difine a function like this

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

And then just use this function like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM