duanlingzei0170 2015-07-23 11:55
浏览 17
已采纳

Symfony2映射适用于一个实体,但不适用于另一个实体

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
  • 写回答

1条回答 默认 最新

  • dongxue163536 2015-07-23 12:35
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?