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?
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:
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:
This way you would get something like:
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.
Check the Serializer/Handler/DoctrineProxyHandler.php file on JMSSerializerBundle. Now, if you comment this line:
It will stop lazy loading your entities. If this is what you're looking for, then just go ahead and create your own handler where you don't lazy load.
If this isn't correct, I recommend that you customize your entities before sending them to JMSSerializerBundle at your taste. For example, in any related entities I want the ID, while in others i need a custom column name like code, or name, or anything.
I just create a copy of my entity object and then start getting the fields I need for relationships. Then, I serialize that copy. JMSSerializerBundle won't lazy load because I already provided the proper fields.
Here is the class which prevent lazy loading of one or many associations which can be used as JMS Serializer ExclusionStrategy.
Usage example:
Here's a function to select the IDs of one-to-one or one-to-many associated entities in a generic way without using joins.
Just an update in the latest version of JMSSerializer, the place you should look at is
JMS\Serializer\EventDispatcher\Subscriber\DoctrineProxySubscriber
instead of
Serializer\Handler\DoctrineProxyHandler
To override the default lazy load behaviour, one should define his own event subscriber.
In your app/config.yuml add this:
you can copy the class from JMS\Serializer\EventDispatcher\Subscriber\DoctrineProxySubscriber to Your\Bundle\Event\DoctrineProxySubscriber and comment out the $object->__load(); line
Update: I ended up writing my own simplified version of serialisation tool: https://github.com/dlin-me/array-converter-bundle