属性 中的注释“@OneToMany”从未被导入(Doctrine2)

The annotation "@OneToMany" in property was never imported (Doctrine2)

我正在使用 Doctrine 2 作为 Slim 3 的 ORM,但是当我尝试实现双向关系时,我总是卡在对象映射部分

/**
 * Class Resource
 * @package App
 * @ORM\Entity
 * @ORM\Table(name="users", uniqueConstraints={@ORM\UniqueConstraint(name="user_id", columns={"user_id"})}))
 */
class User
{
    /**
     * @ORM\ManyToOne(targetEntity="UserRoles", inversedBy="users")
     * @ORM\JoinColumn(name="role_id", referencedColumnName="user_role_id")
     */
    protected $user_role;
}

/**
 * Class Resource
 * @package App
 * @ORM\Entity
 * @ORM\Table(name="user_roles", uniqueConstraints={@ORM\UniqueConstraint(name="user_role_id", columns={"user_role_id"})}))
 */
class UserRoles
{
    /**
     * @ORM\OneToMany(targetEntity="User", mappedBy="user_role")
     */
    protected $users;

    public function __construct()
    {
        $this->users = new ArrayCollection();
    }
}    

我在尝试时遇到异常 php vendor/bin/doctrine orm:schema-tool:update --force

输出为:

[Doctrine\Common\Annotations\AnnotationException][Semantical Error] The annotation "@OneToMany" in property App\Entity\UserRoles::$users was never imported. Did you maybe forget to add a "use" statement for this annotation?

主义类喜欢

Doctrine\ORM\Mapping 命名空间的一部分。

您应该使用 ORM 作为别名导入此命名空间。然后你应该在这些 类 前面添加 @ORM 作为注释以使它们起作用。

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\ManyToOne(...)
 * @ORM\JoinColumn(...)
 */

如果您只想使用其中的每一个 类,则必须分别导入。

use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\JoinColumn;

/**
 * @ManyToOne(...)
 * @JoinColumn(...)
 */