【问题标题】:How to save additional entity while persisting another in Doctrine?如何在 Doctrine 中坚持另一个实体的同时保存其他实体?
【发布时间】:2015-06-01 09:00:25
【问题描述】:

我有一个Place 实体和一个Distance 实体,如下所示:

class Place
{
    /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */
    private $id;

    /** @ORM\Column(type="string", length=62, nullable=false) */
    private $name;

    /** @ORM\OneToMany(targetEntity="Distance", mappedBy="origin") */
    protected $distancesTo;

    /** @ORM\OneToMany(targetEntity="Distance", mappedBy="destination") */
    protected $distancesFrom;
}

class Distance
{
    /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */
    private $id;

    /** @ORM\ManyToOne(targetEntity="Place", inversedBy="distancesTo") */
    protected $origin;

    /** @ORM\ManyToOne(targetEntity="Place", inversedBy="distancesFrom") */
    protected $destination;

    /** @ORM\Column(type="integer") */
    private $miles;
}

我希望每次保存一个新的Distance(从 Place_A 到 Place_B)时,反向距离(从 Place_B 到 Place_A)也会插入数据库中。我该怎么做?

【问题讨论】:

    标签: symfony orm doctrine-orm doctrine


    【解决方案1】:

    您需要创建监听器并监听Distance 实体上的持久性。虽然它仍然存在,但您可以使用反向路由创建新的 Distance

    【讨论】:

    • 谢谢@MichaelSivolobov。你能详细说明“听坚持”吗?我应该听哪个事件,prePersistpostPersist,另一个?另外,对于事件监听器,是使用 LifeCycle 回调还是适当的分离事件监听器更好?
    • 我认为这并不重要,因为您将与另一个实体合作。但我建议您使用prePersist,因为您将在一个事务中执行查询。 LifeCycle 回调不是为了这个目的。当您需要在实体中进行一些修改时,可以使用它们。
    • 我为prePersist 事件创建了一个事件监听器,但我是stuck with an infinite loop
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多