Doctrine2一对多/多对一关系

8
因此,1:M / M:1关系的工作方式与M:M关系的工作方式不同(显然),但我认为通过适当的配置,您可以获得与M:M关系相同的输出。
基本上,我需要在path_offer中添加另一个字段(position)。
我以为我已经使其工作了,直到我尝试使用$path->getOffers(),它返回一个PersistentCollection而不是我认为被强制的(Offer的ArrayCollection)。 无论如何,在当前表格内,我有两个条目:一个路径对应两个优惠。 $path->getOffers()返回一个PathOffer的PersistantCollection,其中只附加了一个Offer而不是两个。
我的问题是如何真正使用这些类型的关系? 因为我需要它与我正在工作的项目的许多其他方面(许多M:M集合也需要定位)
我的代码如下!

Path.php

[..]

/**
 * @ORM\Entity
 * @ORM\Table(name="path")
 */
class Path
{
    /**
     * @var integer
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * @ORM\OneToMany(targetEntity="PathOffer", mappedBy="offer", cascade={"all"})
     */
    protected $offers;

[..]

PathOffer.php

[..]

/**
 * @ORM\Entity
 * @ORM\Table(name="path_offer")
 */
class PathOffer
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="Path", inversedBy="offers", cascade={"all"})
     */
    protected $path;

    /**
     * @ORM\ManyToOne(targetEntity="Offer", inversedBy="offers", cascade={"all"})
     */
    protected $offer;

    /**
     * @ORM\Column(type="integer")
     */
    protected $pos;

[..]

Offer.php

[..]

/**
 * @ORM\Entity
 * @ORM\Table(name="offer")
 */
class Offer
{
    /**
     * @var integer
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * @var \ZGoffers\MainBundle\Entity\PathOffer
     *
     * @ORM\OneToMany(targetEntity="PathOffer", mappedBy="path", cascade={"all"})
     */
    protected $paths;

[..]

2
我终于找到了一个解决方法。您可以查看源代码http://www.prowebdev.us/2012/07/symfnoy2-many-to-many-relation-with.html - pmoubed
2个回答

4

我解决了这个问题。希望这篇文章能够帮助其他像我一样感到沮丧的人!

Path.php

<?php

namespace JStout\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="path")
 */
class Path
{
    /**
     * @var integer
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var \JStout\MainBundle\Entity\PathOffer
     *
     * @ORM\OneToMany(targetEntity="PathOffer", mappedBy="path", cascade={"all"})
     * @ORM\OrderBy({"pos" = "ASC"})
     */
    private $offers;

    [...]

PathOffer.php

<?php

namespace JStout\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="path_offer")
 */
class PathOffer
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Path", inversedBy="offers", cascade={"all"})
     */
    private $path;

    /**
     * @ORM\ManyToOne(targetEntity="Offer", inversedBy="paths", cascade={"all"})
     */
    private $offer;

    /**
     * @ORM\Column(type="integer")
     */
    private $pos;

    [...]

Offer.php

<?php

namespace JStout\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="offer")
 */
class Offer
{
    /**
     * @var integer
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var \JStout\MainBundle\Entity\PathOffer
     *
     * @ORM\OneToMany(targetEntity="PathOffer", mappedBy="offer", cascade={"all"})
     */
    private $paths;

    [...]

And for my frontend logic:

PathController.php

<?php

    [...]

    /**
     * @Extra\Route("/path", name="admin_path")
     * @Extra\Route("/path/{id}/edit", name="admin_path_edit", requirements={"id" = "\d+"})
     * @Extra\Template()
     */
    public function pathAction($id = null)
    {
        $path = $this->_getObject('Path', $id); // this function either generates a new entity or grabs one from database depending on $id

        $form = $this->get('form.factory')->create(new Form\PathType(), $path);
        $formHandler = $this->get('form.handler')->create(new Form\PathHandler(), $form);

        // process form
        if ($formHandler->process()) {
            $this->get('session')->setFlash('notice', 'Successfully ' . ($this->_isEdit($path) ? 'edited' : 'added') . ' path!');
            return $this->redirect($this->generateUrl('admin_path'));
        }

        return array(
            'path' => $path,
            'form' => $form->createView(),
            'postUrl' => !$this->_isEdit($path) ? $this->generateUrl('admin_path') : $this->generateUrl('admin_path_edit', array('id' => $path->getId())),
            'paths' => $this->_paginate('Path'),
            'edit' => $this->_isEdit($path) ? true : false
        );
    }

    [...]

PathType.php(路径表单)

<?php

namespace JStout\MainBundle\Form;

use Symfony\Component\Form\AbstractType,
    Symfony\Component\Form\FormBuilder;

class PathType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('title')
            ->add('offers', 'collection', array(
                'type' => new PathOfferType(),
                'allow_add' => true,
                'allow_delete' => true
            ))
            ->add('active');
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'JStout\MainBundle\Entity\Path'
        );
    }
}

PathOfferType.php(路径类型的优惠集合类型)

<?php

namespace JStout\MainBundle\Form;

use Symfony\Component\Form\AbstractType,
    Symfony\Component\Form\FormBuilder;

class PathOfferType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('offer', 'entity', array(
                'class' => 'JStout\MainBundle\Entity\Offer',
                'query_builder' => function($repository) { return $repository->createQueryBuilder('o')->orderBy('o.name', 'ASC'); },
                'property' => 'name'
            )) 
            ->add('pos', 'integer');
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'JStout\MainBundle\Entity\PathOffer'
        );
    }
}

PathHandler.php(我如何处理表单)

<?php

namespace JStout\MainBundle\Form;

use JStout\MainBundle\Component\Form\FormHandlerInterface,
    Symfony\Component\Form\Form,
    Symfony\Component\HttpFoundation\Request,
    Doctrine\ORM\EntityManager,
    JStout\MainBundle\Entity\Path;

class PathHandler implements FormHandlerInterface
{
    protected $form;
    protected $request;
    protected $entityManager;

    public function buildFormHandler(Form $form, Request $request, EntityManager $entityManager)
    {
        $this->form = $form;
        $this->request = $request;
        $this->entityManager = $entityManager;
    }

    public function process()
    {
        if ('POST' == $this->request->getMethod()) {
            // bind form data
            $this->form->bindRequest($this->request);

            // If form is valid
            if ($this->form->isValid() && ($path = $this->form->getData()) instanceOf Path) {
                // save offer to the database
                $this->entityManager->persist($path);

                foreach ($path->getOffers() as $offer) {
                    $offer->setPath($path);
                    $this->entityManager->persist($offer);
                }

                $this->entityManager->flush();

                return true;
            }
        }

        return false;
    }
}

17
你能描述一下它们的区别吗? - martin

2

看起来你做得很对。不用担心PersistentCollection/ArrayCollection这些东西,重要的是它们都是集合。

$Path->getOffers()确实应该返回一个PathOffers集合,每个PathOffer都应该有一个优惠。

所以它应该像这样工作:

//Output a all offers associated with a path, along with the position.
$pathOffers = $path->getOffers();

foreach($pathOffers as $po){
    echo $po->getOffer()->id . ' [' . $po->getPosition() . "]\n";
} 

我有什么遗漏吗?


这是我的数据库条目 http://bit.ly/j3jcyy,$path->getOffers()输出:object(Doctrine\ORM\PersistentCollection)#755 (9) { ["snapshot":"Doctrine\ORM\PersistentCollection":private]=> array(0) { } 这意味着 $pathOffers[0] 为空。 - Jordan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接