SuperCabbage SuperCabbage - 4 months ago 15
PHP Question

Bidirectional OneToOne relation in Symfony2

Outline of Problem



I'm having some issues creating a bidirectional OneToOne relationship in Symfony2 using Doctrine2. My database has two tables I'm trying to relate, CrmCapacity and CrmPackages, CrmCapacity has a field PackageId which matches to the Id field in CrmPackages.

I am able to get a capacity from a package, but I don't seem to be able to get a package from a capacity, as the relationship stands it's one directional not bidirectional.

Following is the code in my controller, this works just fine to access a capacity from a package.

$package = $this->getDoctrine()
->getRepository('LargeAzureBundle:Package')
->find('ID-HERE');

var_dump($package->getName());
var_dump($package->getCapacity()->getIsIncompleteReason());
die();


That works fine, however the following fetches data for Capacity but not for Package

$capacity = $this->getDoctrine()
->getRepository('LargeAzureBundle:Capacity')
->find('3FF564FC-5EA0-E211-B8AC-005056B70002');

var_dump($capacity->getIsIncompleteReason());
var_dump($capacity->getPackage()->getName());
die();


Entities



Following are the annotations from my entities

Package

class Package {
/**
* @OneToOne(targetEntity="Capacity", mappedBy="Package")
*/
protected $Capacity;

--SNIP--
}


Capacity

class Capacity {
/**
* @OneToOne(targetEntity="Package", inversedBy="Capacity")
* @JoinColumn(name="PackageId", referencedColumnName="Id")
*/
protected $Package;

--SNIP--
}


Any ideas? I'm a bit stumped on this one.

Answer

Managed to get an answer from memoryleak on the Symfony IRC channel. Setting a fetch attribute on the annotation worked in this case, for example;

class Capacity {
    /**
     * @OneToOne(targetEntity="Package", inversedBy="Capacity", fetch="EAGER")
     * @JoinColumn(name="PackageId", referencedColumnName="Id")
     */
    protected $Package;

    --SNIP--
}
Comments