【问题标题】:Symfony 2 - Get additional fields in Many-to-Many relationshipSymfony 2 - 在多对多关系中获取附加字段
【发布时间】:2014-07-22 19:31:09
【问题描述】:

我在 Symfony 2 中有一个多对多关系。下图。

http://i.stack.imgur.com/x6AYs.png

从 Tema Entity 我可以获取所有使用此 ORM 定义相关的 Topico 记录

/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\ManyToMany(targetEntity="Application\RiesgoBundle\Entity\Topico", inversedBy="tema")
 * @ORM\JoinTable(name="tema_topico",
 *   joinColumns={
 *     @ORM\JoinColumn(name="tema", referencedColumnName="id")
 *   },
 *   inverseJoinColumns={
 *     @ORM\JoinColumn(name="topico", referencedColumnName="id")
 *   }
 * )
 */
private $topico;

并使用这种方法

/**
 * Get topico
 *
 * @return \Doctrine\Common\Collections\Collection 
 */
public function getTopico()
{
    return $this->topico;
}

但是,我不知道如何访问存储在 tema_topico 表中的“impacto”和“ocurrencia”值。有没有办法使用实体管理器来做到这一点?

【问题讨论】:

    标签: symfony doctrine many-to-many entitymanager


    【解决方案1】:

    在多对多关联中,您不能存储额外的字段。要实现带有额外字段的“ManyToMany”,您必须执行 OneToMany - ManyToOne。它会给你类似的东西。

    class Tema {
        /*
         * @ORM\OneToMany(targetEntity="temaTopico", mappedBy="tema")
         */
        private $temaTopico;
    }
    
    class Topico {
        /*
         * @ORM\OneToMany(targetEntity="temaTopico", mappedBy="topico")
         */
        private $temaTopico;
    }
    
    class TemaTopico {
        /*
         * @ORM\Id()
         * @ORM\ManyToOne(targetEntity="Tema", inversedBy="temaTopico")
         */
        private $tema;
    
        /*
         * @ORM\Id()
         * @ORM\ManyToOne(targetEntity="Topico", inversedBy="temaTopico")
         */
        private $topico;
    
        /*
         * @ORM\Column(name="impacto", type="string")
         */
        private $impacto;
    }
    

    thisthis

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-10
      • 2012-03-25
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 2021-10-14
      相关资源
      最近更新 更多