doctrine2 association is not initialized

后端 未结 4 1891
执笔经年
执笔经年 2020-12-16 06:33

I have a Class like the following:

/** @Entity **/
class orgGroup{

    //id and stuff...

    /**
     * @Column(type=\"string\")
     **/
    private $name         


        
相关标签:
4条回答
  • 2020-12-16 07:21

    Try to change fetch mode to EAGER.

    @ORM\ManyToOne(targetEntity="****", fetch="EAGER"). 
    

    It worked for me.

    0 讨论(0)
  • 2020-12-16 07:22
    //Group.php ...
    
    public function addUser(User $user): self
    {
        if (!$this->users->contains($user)) {
            $this->users[] = $user;
            $user->addJoinedGroup($this);     /** VERY IMPORTANT **/
        }
        return $this;
    }
    

    Same in User.php Without it, it didn't do anything in my database

    0 讨论(0)
  • 2020-12-16 07:24

    Be sure to initialize the orgGroups collection in the orgGroupType entity

    /**
     * @OneToMany(targetEntity="orgGroup", mappedBy="_orgGroupType")
     */
    protected $orgGroups ;
    
    public function __construct() {
        $this->orgGroups = new ArrayCollection();
    }
    

    You might need to include the following in the Entity

    use Doctrine\Common\Collections\Collection,
    Doctrine\Common\Collections\ArrayCollection;
    
    0 讨论(0)
  • 2020-12-16 07:29

    This looks to me like a lazy-loading-issue. How do you get the data from the object into the Webservice answer?

    Doctrine2 is lazy-loading if you don't configure something else, that means your $groups = $em->getRepository("orgGroup")->findAll(); won't return real orgGroup objects, but Proxy objects (Doctrine Documentation).

    That means a $group object won't have it's description or orgGroupType value until you call $group->getDescription() or $group->getOrgGroupType() (then Doctrine loads them automatically), so you need to do that before writing the data into the JSON-response for the webservice. It won't work if you somehow loop through the object properties without using the getter methods.

    I hope that was the problem :)

    0 讨论(0)
提交回复
热议问题