Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

php - Avoiding recursion with Doctrine entities and JMSserializer

I am building a REST API using Symfony2, Doctrine, FOSRestBundle and JMSSerializer.

The issue I am having is when serializing my entities, the serializer pulls in any related entities. Eg for a task that is part of a story which is part of a board, so when serializing the task I get output that includes the story which includes the board, which then includes all other stories on the board.

Is there an easy way to limit this, and just include the foreignIds instead?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use JMS exclusion policy.

Example using annotations on category entity, where you don't want to include children and product related entities to be included:

use ...
    JMSSerializerBundleAnnotationExclusionPolicy,
    JMSSerializerBundleAnnotationExclude,
    ...;

/**
 * ...
 * @ExclusionPolicy("none")
 */
class Category
{
   /**
    * ...
    * @Exclude
    */
   private $children;

   /**
    * ...
    * @Exclude
    */
   private $products;

}

Look at the JMSSerializer docs for more information.

EDIT:

For example you could use partial keyword to select only data that you need. Although I could not, for the life of me, disable the loading of the full related entities (two levels down) if I pass entity object to the serializer (even when disabling load in DoctrineProxyHandler), but if I use an array, than it doesn't use doctrine lazy loading though proxies (as expected ofc).

Example using your example entities:

$dql = "SELECT t, s, partial b.{id}, partial ss.{id}
        FROM AcmeAppBundleEntityTask t
        JOIN t.story s
        JOIN s.board b
        JOIN b.stories ss"

$q = $this->_em-createQuery($dql);

$result = $q->getArrayResult();

This way you would get something like:

[
{
    id: 33,
    title: "My Task",
    story: [
    {
        id: 554,
        board: [
        {
            id: 14,
            stories: [
            {
                id: 554
            },
            {
                id: 3424
            },
            {
                id: 3487
            }
            ]
        }
        ]
    }
    ]

}
]

P.S. I'm actually intrigued by this "problem". Anyway I'll see to come up with solution to how to serialize entity object without using array result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...