php - Doctrine2 一对多/多对一关系

标签 php symfony doctrine-orm

因此,1:M/M:1 关系不像 M:M 关系那样工作(很明显),但我认为通过适当的配置,您可以获得与 M:M 关系相同的输出。

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

在我尝试使用 $path->getOffers() 之前,我认为它可以正常工作,它返回了一个 PersistentCollection 而不是我认为是强制的(一个 ArrayCollection of Offers)。无论如何,在当前表中,我有两个条目:一条路径的两个报价。 $path->getOffers() 正在返回一个 PathOfferPersistantCollection,它只有一个 Offer 被附加,而没有两者。

我的问题是如何真正使用这些类型的关系?因为我正在处理的这个项目的许多其他方面都需要它(许多 M:M 集合也需要定位)

我的代码在下面!

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

    [...]

对于我的前端逻辑:

路径 Controller .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 的优惠集合类型)

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

关于php - Doctrine2 一对多/多对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6514365/

相关文章:

php - Doctrine ORM关联的默认值

javascript - 我的 Ajax 调用未定义

php - 用于 Javascript/PHP 开发的最佳编辑器/IDE(?)

php - PhpMyAdmin 中的文件大小达到 34KB 限制

php - 如何在 NelmioAlice 的实体构造函数中设置 ArrayCollection 的固定装置

symfony - 为什么 Doctrine 迁移尝试在多对多关系上创建 2 个表

php - 仅选择页面上链接的相关新闻项(多一二多关系)

PHP算法从单个集合中生成特定大小的所有组合

php - 在 Symfony 中注册特定的表单类型 - Compiler Pass

symfony - INTERVAL 1 MONTH 不使用 symfony2 Doctrine ?