ID not saved in OneToMany relationship

大城市里の小女人 提交于 2021-02-17 05:17:05

问题


I'm working on a project using Symfony2. But I'm running into a problem. I have an entity Purchase and another, TypePurchase. They have an OneToMany-relationship, but when I look inside of the table of TypePurchase, the Purchase entity ID is not saved. It's value is null. I already tried $types->setPurchase($this) in the addType method Purchase. But this gives me the result that only the first added entity get's an ID, the next one is again null.

This is my field and ID field in Purchase:

/**
 * @ORM\OneToMany(targetEntity="TypePurchase", mappedBy="purchase", cascade={"persist", "remove" })
 */
protected $types;

This is what I already added, but is not working fully:

/**
 * Add types
 *
 * @param \Wood\AdminBundle\Entity\TypePurchase $types
 * @return Purchase
 */
public function addType(\Wood\AdminBundle\Entity\TypePurchase $types)
{
    $this->types[] = $types;
    $types->setPurchase($this);
    return $this;
}

And this is my field inside TypePurchase:

/**
 * @ORM\ManyToOne(targetEntity="Purchase", inversedBy="types", cascade={"persist", "remove" })
 * @ORM\JoinColumn(referencedColumnName="id")
 */
protected $purchase;

Edited: My ID field in Purchase

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

This is my createAction in the Purchase controller:

/**
 * @param Request $request
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function createAction(Request $request)
{
    $purchase = new Purchase();
    $purchase->addType(new TypePurchase());
    $form = $this->createForm(new PurchaseType(), $purchase);

    $form->handleRequest($request);
    if($form->isValid()) {
        $purchase->setUser($this->getUser());
        $purchaseService = $this->get('woodadmin.purchaseservice');
        $purchaseService->createPurchase($purchase);

        $flash = $this->get('braincrafted_bootstrap.flash');
        $flash->success('De inkoop is succesvol geregistreerd.');

        $now = time();
        if($purchase->getSupplier() != null) {
            $date = $purchase->getSupplier()->getFscExpiration()->format('U');
            $datediff = $date - $now;
            $diff = floor($datediff / (60 * 60 * 24));

            if ($diff <= 14) {
                $flash->alert('Let op, het FSC-certificaat van de leverancier ' . htmlentities($purchase->getSupplier()->getName()) . ' verloopt bijna of is al verlopen.');
            }

            $now2 = time();
            $date2 = $purchase->getSupplier()->getPefcExpiration()->format('U');
            $datediff2 = $date2 - $now2;
            $diff2 = floor($datediff2 / (60 * 60 * 24));

            if ($diff2 <= 14) {
                $flash->alert('Let op, Het PEFC-certificaat van de leverancier ' . htmlentities($purchase->getSupplier()->getName()) . ' verloopt bijna of is al verlopen.');
            }
        }

        return $this->redirect($this->generateUrl('wood_admin_purchase_list'));
    }
    return $this->render('WoodAdminBundle:Purchase:create.html.twig', array('title' => 'Inkoop registreren', 'page' => 'purchases', 'form' => $form->createView()));
}

My PurchaseService part where I persist the Purchase entity:

public function createPurchase(\Wood\AdminBundle\Entity\Purchase $purchase) {
    $this->entityManager->persist($purchase);
    $this->entityManager->flush();
}

回答1:


You need to persist your TypePurchase entity before you persist your Purchase Entity.

The following example is an extension to the User-Comment example of this chapter. Suppose in our application a user is created whenever he writes his first comment. In this case we would use the following code:

<?php
$user = new User();
$myFirstComment = new Comment();
$user->addComment($myFirstComment);

$em->persist($user);
$em->persist($myFirstComment);
$em->flush();

Even if you persist a new User that contains our new Comment this code would fail if you removed the call to EntityManager#persist($myFirstComment). Doctrine 2 does not cascade the persist operation to all nested entities that are new as well.

http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-associations.html

$purchase = new Purchase();
$typePurchase = new TypePurchase();
$this->enityManager->persist($typePurchase);
$purchase->addType($typePurchase);
$form = $this->createForm(new PurchaseType(), $purchase);


来源:https://stackoverflow.com/questions/28829948/id-not-saved-in-onetomany-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!