Search code examples
phpsymfonydoctrine-ormentitysymfony-3.4

Symfony - belongsTo in same entity


I want to have direct relation between two entity fields from same table.

The idea is to add in my entity manager_id, which will point to another user in user table (I tried with OneToOne.

When user calls the action, user_id to whom to, for example, send the message will be pulled as

$user->getManager()->getId();

Error log says:

No mapping found for field ID.

class User  
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

   /**
    * @ORM\OneToOne(targetEntity="App\Entity\User", 
      mappedBy="id")
    */
   private $manager;

Solution

  • Simple way to create such relation is to use undirectional relation type. Code for it looks like this:

    class User
    {
        /**
         * @var int
         *
         * @ORM\Id
         * @ORM\Column(type="integer")
         * @ORM\GeneratedValue(strategy="AUTO")
         */
         protected $id;
    
        /**
         * @var User
         *
         * @ORM\ManyToOne(targetEntity="App\Entity\User")
         */
         private $manager;
    }
    

    Now you can do:

    /** @var User $user */
    $managerId = $user->getManager()->getId();
    

    Hope this helps.

    PS. I added some @var docblocks for hinting.