Home > database >  Doctrine: how to describe manyToOne relation with composite key and update cascade?
Doctrine: how to describe manyToOne relation with composite key and update cascade?

Time:11-15

I have a table that has composite primary key: id est_date. And it has an entity:

class Parent
{
    /**
     * @ORM\Id
     */
    private $id;

    /**
     * @ORM\Id
     */
    private int $estDate;
...
}

Now I need to create a related table and its entity.

class Child
{
...
    /**
     * don't know what to write here
     */
    private $parentId;

    /**
     * don't know what to write here
     */
    private int $parentEstDate;
...
}

How to discribe relation ManyToOne (many "Child" entities may relate to 1 "Parent")? And the second issue is - "estDate" of the "Parent" may change. How to specify cascade update in "Child"? Please don't write that doctrine doesn't recomment to use composite keys. I know that.

CodePudding user response:

on the child-entity you would refer to the parent entity the same way as with single columns, essentially. Starting with

annotation version:

/**
 * @ORM\ManyToOne(targetEntity=Parent::class)
 */
private ?Parent $parent;

since the child is the owning side, you have to provide join columns, as you have noticed. There is a badly documented annotation JoinColumns that allows to define multiple join columns. (Note for those using the attribute syntax instead: you should be able to have multiple #[JoinColumn(...)], without the JoinColumns-Wrapper)

annotation version:

/**
 * @ORM\ManyToOne(targetEntity=Parent::class)
 * @ORM\JoinColumns({
 *    @ORM\JoinColumn("parent_id", referencedColumnName="id"),
 *    @ORM\JoinColumn("parent_est_date", referencedColumnName="est_date")
 * })
 */
private ?Parent $parent;

If you want to add the inverse side as well, you always reference the object property, not the columns when using mappedBy/inversedBy.

Generally with doctrine-orm: Your class/object should not care about columns, only about php stuff, doctrine should handle the rest. The annotations tell doctrine, how this converts to columns. So not every column will get its own property in this case.

  • Related