12

I'm working with Doctrine 2 as an ORM for Slim 3 but I keep getting stuck in the object mapping section when I try to implement a bidirectional relationship

/**
 * 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();
    }
}    

I get an exception when I try php vendor/bin/doctrine orm:schema-tool:update --force

The output is:

[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?

danopz
  • 3,310
  • 5
  • 31
  • 42
clifford_owino
  • 462
  • 1
  • 6
  • 24

1 Answers1

31

Doctrine classes like

are part of the Doctrine\ORM\Mapping namespace.

You should import this namespace with ORM as an alias. Then you should add @ORM in front of these classes as annotation to make them work.

use Doctrine\ORM\Mapping as ORM;

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

If you just want to use every single of those classes you have to import each separately.

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

/**
 * @ManyToOne(...)
 * @JoinColumn(...)
 */
danopz
  • 3,310
  • 5
  • 31
  • 42