FOSUserBundle: UniqueEntity annotation throws: The field "User" is not mapped by Doctrine, 因此无法验证其唯一性

FOSUserBundle: UniqueEntity annotation throws: The field "User" is not mapped by Doctrine, so it cannot be validated for uniqueness

我有一个实体 Employee,外键来自 User。 我正在使用 FOSUserBundle。

我想在 UserEmployee 之间实现唯一的一对一关系。

我尝试添加 UniqueEntity 注释,但出现以下错误:

"The field "User" is not mapped by Doctrine, so it cannot be validated for uniqueness."

我发现问题是 User 实体使用 ...

use FOS\UserBundle\Model\User as BaseUser; 

...而不是...

use FOS\UserBundle\Entity\User as BaseUser;

但我不知道我必须覆盖什么,因为捆绑包中的这个实体不存在..

/**
 * Employee
 * @ORM\Table(name="employee")
 * @ORM\Entity
 * @UniqueEntity(
 * fields={"User"},
 * errorPath="User",
 * message="This account is assigned"
 * )
 */
class Employee {

    /**
     * @var User
     *
     * @ORM\ManyToOne(targetEntity="User")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="user_id", referencedColumnName="id",unique=true)
     * })
     */
    private $myUser;

}

namespace App\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    public function __construct()
    {
        parent::__construct();
        // your own logic
    }   
    function getId() {
        return $this->id;
    }

    function setId($id) {
        $this->id = $id;
    }

    public function getUsername() {
        return $this->username;
    }
}

您引用的是 class-name 而不是 属性-name Employee class 在 @UniqueEntity 定义中 fields.

注释的正确配置是 fiels={"myUser"} 而不是 User

/**
 * @UniqueEntity(
 *   fields={
 *     "myUser"
 *   },
 *   errorPath="myUser",
 *   message="This account is assigned"
 * )
 */
class Employee {

    /**
     * [..]
     */
    private $myUser;