I think I’m missing something obvious with doctrine relationship mapping.
I have two models, Microsite and Page (one to many, page only belongs to one site).
/*
...
* @ORM\Table()
* @ORM\Entity(repositoryClass="EP\PreReg\DataBundle\Entity\MicrositeRepository")
*/
class Microsite
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
...
/**
* @ORM\OneToMany(targetEntity="Page", mappedBy="site")
*/
private $pages;
public function __construct() {
$this->pages = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getPages() {
return $this->pages;
}
public function addPage($page) {
$this->pages[] = $page;
}
/*
* @ORM\Table()
* @ORM\Entity
*/
class Page
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string $title
*
* @ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* @var string $slug
*
* @ORM\Column(name="slug", type="string", length=100)
*/
private $slug;
/**
* @ORM\ManyToOne(targetEntity="Microsite", inversedBy="pages")
*/
private $site;
The schema looks good:
CREATE TABLE Page (id INT AUTO_INCREMENT NOT NULL, site_id INT DEFAULT NULL, title VARCHAR(255) NOT NULL, slug VARCHAR(100) NOT NULL, INDEX IDX_B438191EF6BD1646 (site_id), PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE Microsite (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, shortCode VARCHAR(20) NOT NULL, subdomain VARCHAR(100) NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB;
ALTER TABLE Page ADD CONSTRAINT FK_B438191EF6BD1646 FOREIGN KEY (site_id) REFERENCES Microsite(id)
but I can’t get the fixtures to load properly (I had them working, but even then I could not get the related pages per site.
My question is: Are these annotations correct, and how do I correctly add data, and retrieve pages from a given site?
Fixtures are:
class LoadMicrositeData implements FixtureInterface
{
public function load(ObjectManager $manager)
{
$site = new Microsite();
$site->setName('Microsite Name');
$site->setShortCode('MIC');
$site->setSubdomain('micro');
$homepage = new Page();
$homepage->setSlug('/');
$homepage->setTitle('Welcome');
$site->addPage($homepage);
$manager->persist($site);
$manager->persist($homepage);
$manager->flush();
}
}
You need to set the
$siteproperty on thePage. I advise you to delegate the creation of a Page to the Microsite:You would then use it this way: