简体   繁体   中英

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?

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM