简体   繁体   中英

symfony2 doctrine manytoone relationship

I believe it's that there must be a simple solution for my issue but I can't get that to work and I'm not sure why.

Scenario: I've got 2 entities: Bike and Review, relationship is OneToMany:

/**
 * Bike
 *
 * @ORM\Entity(repositoryClass="BikeRepository")
 * @ORM\HasLifecycleCallbacks
 * @ORM\Table(name="bike")
 */
class Bike
{
...
    /**
     * @var string
     *
     * @ORM\OneToMany(targetEntity="Review", mappedBy="bike", cascade={"persist"}, fetch="EXTRA_LAZY")
     */
    private $reviews;
...
}

/**
 * Review
 *
 * @ORM\Entity(repositoryClass="ReviewRepository")
 * @ORM\Table(name="review")
 * @ORM\HasLifecycleCallbacks()
 */
class Review
{
    ...

    /**
     * @var integer
     *
     * @ORM\ManyToOne(targetEntity="Bike", inversedBy="reviews", fetch="EXTRA_LAZY")
     * @ORM\JoinColumn(name="bike_id", referencedColumnName="id")
     */
    private $bike;
    ....
}  

Getters and setters has been generated by doctrine.

On the frontend I've got a form where bike is as a hidden field because there is an autocomplete field with ajax request. So in the controller if $form->isValid() I'm getting bike id from the hidden field, search database for that bike and set bike as below:

if ($form->isValid()) {
    if ($bikeId) {
        $bike = $this->em->getRepository('BikeBundle:Bike')->findOneBy(array('id' => $bikeId));
        $review->setBike($bike);
    }
    $this->em->persist($review);
    $this->em->flush();
}  

And this is always giving me NULL in the database for bike_id. Any idea what could be wrong? I have tried to dump $review before persist and I can get the bike details so I don't know what's going wrong. In the entity setBike() method I can get any value of that Bike object except getId() is returning NULL.

Thanks for any help.

  1. you don't need to persist an existing entity, so you can just save your entity like

    $review->setBike($bike); $this->em->flush();

  2. try to check if doctrine really returns any entities..I'm afraid if it doesn't return Bike entity

UPD: Also try to check the namespace of Bike Entity class. It seems like it is wrong in your case, because usually it looks like "AcmeBikeBundle:Bike"

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