smartcoderx
smartcoderx

Reputation: 1081

Many to many relation can get associated object

I have a user and a school entity. This both entities have a many to many relation.

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

    /**
         * @ORM\ManyToMany(targetEntity="AppBundle\Entity\School")
         * @ORM\JoinTable(name="user_school",
         *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
         *      inverseJoinColumns={@ORM\JoinColumn(name="school_id", referencedColumnName="id")}
         *      )
         */
        private $school;

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

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

        public function getId()
        {
            return $this->id;
        }
    }

If i call the method for retriving the school id in my controller like:

    public function indexAction(Request $request)
    {
        $user = $this->getUser();
        $school = $user->getSchool();
        echo $school->getId();
    }

I get the error message

Attempted to call an undefined method named "getId" of class "Doctrine\ORM\PersistentCollection"

Can someone give me hint , what i'm doing wrong?

Upvotes: 0

Views: 242

Answers (2)

Terenoth
Terenoth

Reputation: 2598

In the mapping you defined, User::$school is a ManyToMany, which means the result of getSchool will be a Collection of Schools, not a single School entity.

Two scenarios:

  1. A User can have multiple Schools. Then you probably should rename $school to $schools and getSchool to getSchools. And you can't call $user->getSchools()->getId() since $user->getSchools() is a Collection and does not have a getId method. Check @NoyGabay's answer for a way to access Schools ids.

  2. A User can only have one School. Then you did not define your mapping correctly; you wanted a ManyToOne instead of ManyToMany. Check Doctrine's documentation for association mapping.

Upvotes: 0

Noy
Noy

Reputation: 1268

Even though $user->getSchool(); is singular in method name, it returns a PersistentCollection - a collection of schools (since the relationship is ManyToMany). If you want to get a specific school's id, you would have to iterate through the schools, like so:

$scools = $user->getSchool()->toArray();
foreach ($scools as $scool) {
    // do something with $school
}

Upvotes: 2

Related Questions