Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Accessing One-To-Many Relation in Symfony 2 with Doctrine

I've got a simple One-to-Many relation that errors out when I try to iterate through the collection.

from the "One" User.php

    /**
     * @ORM\OneToMany(targetEntity="UserMeasurement", mappedBy="measurements")
     */
    protected $measurements;

And the corresponding "Many" UserMeasurement.php:

    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="measurements", cascade={"persist"})
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    protected $user;

and yet when I try to run from a command:

    $query = $em->createQuery(" SELECT user FROM AcmeFooBundle:User user");
    $users = $query->getResult();
    foreach ($users as $user) {
        print count($user->getMeasurements()->toArray());
    }

I get the following error:

[ErrorException]
Notice: Undefined index: measurements in /Applications/MAMP/htdocs/Symfony/vendor/doctrine/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 1280

I've run the doctrine:schema:update --force command and it says I'm in sync.

Am I iterating incorrectly?

like image 858
Simon Avatar asked Mar 05 '12 19:03

Simon


1 Answers

In your User entity, you have this line:

@ORM\OneToMany(targetEntity="UserMeasurement", mappedBy="measurements")

What you're telling Doctrine is that it should look in the UserMeasurement entity for a field named measurements, which doesn't exist. What you probably intended was this:

@ORM\OneToMany(targetEntity="UserMeasurement", mappedBy="user")
like image 190
Derek Stobbe Avatar answered Nov 02 '22 20:11

Derek Stobbe