symfony many to many orm controller

260 views Asked by At

I have a many-to-many relationship this is my table

site
------
id
name


site_landingpage
---------------
id
site_id
landingpage_id


landingpage
----------
id
name


Page.php
-----------------------
 /**
 * @ORM\ManyToMany(targetEntity="Page\DefaultBundle\Entity\Site", mappedBy="landingpages")
**/
    private $sites;


Site.php
/**
     * @ORM\ManyToMany(targetEntity="Site\PageBundle\Entity\Page", inversedBy="sites")
     * @ORM\JoinTable(name="site_landingpage")
     **/

    private $landingpage;

If I add a landingpage it should get the current site and populate site_landingpage table how am I able to do this in the controller part where you add a landingpage given that my site_id is $site_id

1

There are 1 answers

2
Maltronic On

I'm not sure if your entities have their getters & setters created, if not generate them by running:

app/console doctrine:generate:entities PageBundle:Site
app/console doctrine:generate:entities PageBundle:Page

Then you can simply do something like:

$landingpage = new Page();
$site->addLandingpage($landingpage);

This blog post by Kontroversial Keith provides a detailed example of populating many-to-many relationship entities from user input.

As a side note, join tables (ie site_landingpage) don't need an extra id column (although shouldn't break anything), simply have site_id & landingpage_id as a joint primarykey.