Search code examples
laravelormdoctrine-ormdoctrineone-to-one

Why is this Doctrine OneToOne Self-referencing Bidirectional association not working?


We have two entities using InheritanceType("SINGLE_TABLE").

The parent class that defines the DiscriminatorMap is Note. The two children are Comment and Message.

There are cases where we would like to copy a comment from a message.

We wanted to indicate where this occurred so we added a column called copied_to_id. And every time we copy a message to a comment we set the messages's copied_to_id to the newly created comment's id.

Now we added an association to the Message entity like such...

    /**
     * @var Comment
     *
     * @ORM\OneToOne(targetEntity=Comment::class, inversedBy="copiedFrom")
     * @ORM\JoinColumn(name="id", referencedColumnName="copied_to_id", nullable=true)
     */
    protected $copiedTo;

Everything worked nicely and we were able to get the newly created comment by requesting $message->copiedTo. However that all changed once we added the inversedBy part here as well as in the Comment class. We wanted to the ability to get inverse of the relationship by using $comment->copiedFrom.

    /**
     * @var Message
     *
     * @ORM\OneToOne(targetEntity=Message::class, mappedBy="copiedTo")
     */
    protected $copiedFrom;

Once we did that it stopped working not only is the copied from null, but when we query for Comments it's only returning one comment (instead of the 7 that should be returned).

Are we correct that this is the way to set up this type of OneToOne relationship? If yes what are we possibly doing wrong?

(We set up this relationship in eloquent and it was a breeze, so we think it's correct)

We tried moving around the association and playing with whose the mappedBy and inversedBy as well as changing up the JoinColumn id and referencedColumnName but nothing seems to work.

The example in the docs seems to be set up similar to the one I've described.

In this article I notice it mentions about one to one cannot lazy load the inverse. Maybe this is the issue we're having, but then what would be a work around for this?

Doctrine: 2.13.1 Laravel-Doctrine: 1.7.9


Solution

  • Apparently this is a know issue.

    Options 4 and 6 from this post are workarounds that seem to work.