簡體   English   中英

Doctrine2 一對多/多對一關系

[英]Doctrine2 One-To-Many / Many-To-One relations

因此,1:M / M:1 關系不像 M:M 關系那樣工作(顯然),但我認為通過適當的配置,您可以獲得與 M:M 關系相同的 output 。

基本上,我需要向path_offer添加另一個字段(位置)。

我以為我可以讓它工作,直到我嘗試使用$path->getOffers()它返回一個PersistentCollection而不是我認為是強制的(一個ArrayCollection of Offers)。 無論如何,在當前表中,我有兩個條目:一個路徑的兩個提議。 $path->getOffers()正在返回一個PathOfferPersistantCollection ,它只附加了一個Offer ,而不是兩者。

我的問題是如何真正使用這些類型的關系? 因為我正在處理的這個項目的許多其他方面都需要它(許多 M:M collections 也需要定位)

我的代碼如下!

路徑.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;

[..]

報價.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;

[..]

我想到了。 希望這篇文章可以幫助其他和我一樣沮喪的人!

路徑.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;

    [...]

報價.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;

    [...]

對於我的前端邏輯:

路徑控制器.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(PathType的offers集合類型)

<?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;
    }
}

看起來你做對了。 不要擔心PersistentCollection / ArrayCollection的東西——重要的是它們是 collections。

$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";
} 

我錯過了什么嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM