Jimbo Jimbo - 8 days ago 5
PHP Question

Doctrine oneToMany relationship results in null for foreign key on inverse entity when serializing


Relevant information: I'm using Symfony 2.8.x, Doctrine 2.4.8 and JMSSerializerBundle 1.0.


A
Resource
can have many
Experiences
. I'm making an API Call to retrieve a
Resource
and all associated
Experience
s.

However, the JSON I get back contains a
null
on
$resource
on the
Experience
entity.

I'm using the the following method to retrieve the
Resource
:

$this->findBy([], [], $limit, $offset);


I don't believe this should be an issue because I've tried setting the fetch mode to
EAGER
directly in the annotations - this still hasn't worked. I've also cleared the cache.

Resource.orm.yml



oneToMany:
experiences:
targetEntity: Experience
mappedBy: resource
fetch: EAGER


Experience.orm.yml



resource:
targetEntity: Resource
inversedBy: experiences
joinColumn:
name: resource_id
referencedColumnName: id
fetch: EAGER
fetch: EAGER


See I've tried ALL the eager fetches!!

Response



The response I get when making an API request for this json:

{
"resources": [{
"id": 1,
# SNIP #
"experiences": [{
"resource": null,
"id": 1,
# SNIP #
}]
}]
}


Note the null for resource!

Here's why I think it's a problem with lazy loading: the collection is an instance of
Doctrine\ORM\PersistentCollection
instead of just an array as I expect:

enter image description here

Why is this null?? What is my problem? Have I:


  • Messed up the relationship configuration and this isn't actually anything to do with lazy loading

  • Placed lazy loading in the wrong place

  • Misunderstood and this is a good thing because of recursion?

  • Something else retarded?


VaN VaN
Answer

This is probably the normal behavior for the API and its Serializer (model to JSON transformation).

Why would you need experiences.resource to be filled actually ? You already have it on the root level of the JSON.

If you still want to experiences to fully contain their resource, you probably have to configure the Serializer and force it to go 1 step deeper in serialization. But most of the time, Serializers are configured this way to avoid infinite cycles (resource containing its experiences, containing its resource, containing its experiences, and so on..