Primary key of owning side as a join column

后端 未结 4 720
借酒劲吻你
借酒劲吻你 2020-12-02 15:06

NOTE: Topic is lengthy but detailed and may come in handy if you use Doctrine2 and oneToOne relationships.

Recently I came across a problem in Doctrine:

4条回答
  •  心在旅途
    2020-12-02 15:08

    My workaround was to turn the OneToOne relationship into a ManyToOne (with an associated ArrayCollection), with a custom getter and setter which only sets and returns the 0-th element of the collection:

    /**
     * Set pref
     *
     * @param \MyBundle\Entity\Pref $pref
     * @return Employee
     */
    public function setPref(\MyBundle\Entity\Pref $pref = null) {
        $this->pref[0] = $pref;
    
        return $this;
    }
    
    /**
     * Get pref
     *
     * @return \MyBundle\Entity\Pref 
     */
    public function getPref() {
        return $this->pref[0];
    }
    

    These methods can (seemingly) be used the same as the ones created by a OneToOne relationship.

    doctrine:generate:entities still creates the normal "add" and "remove" methods, but they can be ignored.

    Note: I only recently started using these and currently only to read from the database. I don't know of any side effects from this workaround. I'll update this answer if I notice any.

    This is admittedly an ugly hack. I hope Doctrine fixes this soon so I can go back to using proper OneToOne relationships.

提交回复
热议问题