zf2 doctrine2关系属性不起作用

时间:2012-10-22 09:54:11

标签: php doctrine-orm doctrine zend-framework2

我在用户enitity中有非列属性

/**
 *
 * @ORM\ManyToOne(targetEntity="\Auth\Entity\Company", inversedBy="user")
 * @ORM\JoinColumn(name="companyID", referencedColumnName="id")
 */
protected $company;


/**
 *
 * @ORM\ManyToOne(targetEntity="\Auth\Entity\Role", inversedBy="user")
 * @ORM\JoinColumn(name="roleID", referencedColumnName="id")
 */
protected $role;

我在用户表中没有列角色或公司。 但是我在用户表中有列roleID和companyID,在用户实体中有相应的属性,如下所示

    /**
     * @ORM\Column(type="integer")
     * @ORM\ManyToOne(targetEntity="\Auth\Entity\Role", inversedBy="user") 
     * @ORM\JoinColumn(name="roleID", referencedColumnName="id")    
     */
    protected $roleID;

    /**
     * @ORM\Column(type="integer")
     * @ORM\ManyToOne(targetEntity="\Auth\Entity\Company", inversedBy="user")
     * @ORM\JoinColumn(name="companyID", referencedColumnName="id")     
     */
    protected $companyID;

在用户控制器中,当我尝试使用以下行添加记录时,它会成功添加记录,但没有roleID和companyID

           $userData = array("username" => $username, "pass" => $secPass,
                "salt" => $salt, "companyID" => $companyID,
                "roleID" => $roleID, "cost" => $cost
            );


            $user->populate($userData);
            $this->getEntityManager()->persist($user);
            $this->getEntityManager()->flush();

但如果我从实体用户中删除这两个属性,那么它还会添加roleID和companyID

protected $company;
protected $role;

但我也需要以上属性。我无法理解为什么会发生冲突,

谁有人遇到这个问题?以及如何解决这个问题?任何的想法?

1 个答案:

答案 0 :(得分:1)

在用户实体中更改您的属性,如下所示

/**
 * 
 * @ORM\Column(type="integer")
 */
protected $roleID;

/**
 * 
 * @ORM\Column(type="integer")
 */
protected $companyID;


/**
 *
 * @ORM\ManyToOne(targetEntity="\Auth\Entity\Company", inversedBy="user")
 * @ORM\JoinColumn(name="companyID", referencedColumnName="id")
 */
protected $company;


/**
 *
 * @ORM\ManyToOne(targetEntity="\Auth\Entity\Role", inversedBy="user")
 * @ORM\JoinColumn(name="roleID", referencedColumnName="id")
 */
protected $role;

然后在您的用户控制器中执行以下操作添加。它对我有用

 $company = $this->getEntityManager()->find('Auth\Entity\Company', $companyID);                
    $role = $this->getEntityManager()->find('Auth\Entity\Role', $roleID);                

    $user->username = $username;
    $user->pass = $secPass;
    $user->salt = $salt;
    $user->company = $company;
    $user->role = $role;
    $user->cost = $cost;                

    $this->getEntityManager()->persist($user);
    $this->getEntityManager()->flush();