ID 未保存在 OneToMany 关系中 [英] ID not saved in OneToMany relationship

查看:17
本文介绍了ID 未保存在 OneToMany 关系中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

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

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

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

And this is my field inside TypePurchase:

/**
 * @ORMManyToOne(targetEntity="Purchase", inversedBy="types", cascade={"persist", "remove" })
 * @ORMJoinColumn(referencedColumnName="id")
 */
protected $purchase;

Edited: My ID field in Purchase

/**
 * @ORMId
 * @ORMColumn(type="integer")
 * @ORMGeneratedValue(strategy="AUTO")
 */
protected $id;

This is my createAction in the Purchase controller:

/**
 * @param Request $request
 * @return SymfonyComponentHttpFoundationResponse
 */
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(WoodAdminBundleEntityPurchase $purchase) {
    $this->entityManager->persist($purchase);
    $this->entityManager->flush();
}

解决方案

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

这篇关于ID 未保存在 OneToMany 关系中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆