简体   繁体   中英

Symfony2 mapping works for one entity but not the other

I have two Entitites mapped together.

Skin.php :

/**
 * @var CmsElement
 *
 * @ORM\ManyToOne(targetEntity="CmsElement")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="homepage_id", referencedColumnName="id")
 * })
 */
private $homepage;

CmsElement.php :

/**
 * @var Skin
 *
 * @ORM\ManyToOne(targetEntity="Skin")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="skin_id", referencedColumnName="id")
 * })
 */
private $skinId;

And thats it. My Skin table is mapped correctly, I get the id of the CmsElement. However in my Cmselement I dont get the needed skinId... It always stays NULL. The codes are identical, why doesnt it work?

An example for better understanding:

Skin:

id: 1
homepage_id: 2

CmsElement:

id: 2
skin_id: NULL

In order to set ManyToOne relation, you have to specify it in both ways like this:

// Skin.php
/**
 * @var CmsElement
 *
 * @ORM\OneToMany(targetEntity="CmsElement", mappedBy="skinId")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="homepage_id", referencedColumnName="id")
 * })
 */
private $homepage;

// CmsElement.php :
/**
 * @var Skin
 *
 * @ORM\ManyToOne(targetEntity="Skin", inversedBy="homepage")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="skin_id", referencedColumnName="id")
 * })
 */
private $skinId;

But, please take care of this points:

  • Use $skin instead of $skinId because you are referencing an entity, not only an id property
  • The relation ManyToOne refer to a side with multiple entity linked to a side with one entity, so please define wich is the multiple side and the single one. I assumed that CmsElement was the multiple side so I used ManyToOne on CmsElement and OneToMany to other. But if I was wrong, please invert this.
  • Use a plurial name for attribute at the multiple side. For instance if you set One $skin for Many $homepages, be sure tu use the final "S", it's easier to understand.

Here you can find informations in order to do your relation in the right way: Sf2 Doc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM