Doctrine2 one-to-one relation auto loads on query

前端 未结 6 1708
借酒劲吻你
借酒劲吻你 2020-12-23 12:53

I have a query that looks like this:

My user entity has a one-to-one relation that looks like this:

/**
 * @var UserProfile
 *
 * @ORM\\OneToOne(targ         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 13:39

    As @apfelbox explained... there is no fix for it now.

    I went for a OneToMany solution in a combination with unique key:

    User.php
    
    /**
     * @ORM\OneToMany(targetEntity="TB\UserBundle\Entity\Settings", fetch="EXTRA_LAZY", mappedBy="user", cascade={"all"})
     */
    protected $settings;
    
    /**
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getSettings()
    {
        return $this->settings;
    }
    

    And

    Settings.php
    
    /**
     * @ORM\ManyToOne(targetEntity="TB\UserBundle\Entity\User", fetch="EXTRA_LAZY", inversedBy="settings")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
     */
    protected $user;
    

    And to ensure the uniqueness in Settings.php include:

    use Doctrine\ORM\Mapping\UniqueConstraint;
    

    And add unique index

    /**
     * @ORM\Entity
     * @ORM\Table(name="user_settings", uniqueConstraints={@UniqueConstraint(name="user", columns={"user_id"})})
     */
    class Settings
    

    So when I want to access the user Settings I just need to this (which will fire ONE query ONLY in that specific moment)

    $_settings = $user->getSettings()->current();
    

    I think is the cleanest solution.

提交回复
热议问题