Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Forms 多对一关系:表单验证不';不能在数据库中创建外键_Forms_Symfony_One To Many_Many To One_Bidirectional - Fatal编程技术网

Forms 多对一关系:表单验证不';不能在数据库中创建外键

Forms 多对一关系:表单验证不';不能在数据库中创建外键,forms,symfony,one-to-many,many-to-one,bidirectional,Forms,Symfony,One To Many,Many To One,Bidirectional,我在后分类和子分类之间有一种多对一的关系,如下所示: 子类别实体: namespace VisualImmersion\AdminBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * SubCategory * * @ORM\Table(name="post_category_subcategory") * @ORM\Entity(repositoryClass="VisualImmersion\AdminBundle\Entity

我在后分类和子分类之间有一种多对一的关系,如下所示:

子类别实体:

namespace VisualImmersion\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * SubCategory
 *
 * @ORM\Table(name="post_category_subcategory")
 * @ORM\Entity(repositoryClass="VisualImmersion\AdminBundle\Entity\Repository\SubCategoryRepository")
 */
class SubCategory
{
    /**
     * @var integer
     *
     * @ORM\Column(name="ID", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="\VisualImmersion\AdminBundle\Entity\PostCategory", cascade={"remove", "persist"}, inversedBy="subCategories")
     * @ORM\JoinColumn(referencedColumnName="ID")
     */
    private $postCategory;


    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return SubCategory
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string 
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set category
     *
     * @param \VisualImmersion\AdminBundle\Entity\PostCategory $category
     */
    public function setPostCategory(\VisualImmersion\AdminBundle\Entity\PostCategory $category)
    {
        $this->postCategory = $category;
    }

    /**
     * Get category
     *
     * @return \VisualImmersion\AdminBundle\Entity\PostCategory
     */
    public function getPostCategory()
    {
        return $this->postCategory;
    }
}
后分类实体:

<?php

namespace VisualImmersion\AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * PostCategory
 *
 * @ORM\Table(name="post_category")
 * @ORM\Entity(repositoryClass="VisualImmersion\AdminBundle\Entity\Repository\PostCategoryRepository")
 */
class PostCategory
{
    /**
     * @var integer
     *
     * @ORM\Column(name="ID", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=45, nullable=false)
     */
    private $name;

    /**
     * @ORM\ManyToMany(targetEntity="Post", mappedBy="posts")
     */
    private $posts;

    /**
     * @ORM\OneToMany(targetEntity="SubCategory", mappedBy="postCategory", cascade={"remove", "persist"})
     */
    protected $subCategories;


    public function __construct()
    {
        $this->posts = new \Doctrine\Common\Collections\ArrayCollection();
        $this->subCategories = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function __toString()
    {
        return (String) $this->id;
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return PostCategory
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string 
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Add post
     *
     * @param \VisualImmersion\AdminBundle\Entity\Post $post
     */
    public function addPost(\VisualImmersion\AdminBundle\Entity\Post $post)
    {
        $this->posts[] = $post;
    }

    /**
     * Get posts
     *
     * @return \Doctrine\Common\Collections\ArrayCollection()
     */
    public function getPosts()
    {
        return $this->posts->toArray();
    }

    /**
     * Remove post
     *
     * @param \VisualImmersion\AdminBundle\Entity\Post $post
     */
    public function removePost(\VisualImmersion\AdminBundle\Entity\Post $post)
    {
        $this->posts->removeElement($post);
    }


    /**
     * Add subCategory
     *
     * @param \VisualImmersion\AdminBundle\Entity\SubCategory $subCategory
     */
    public function addSubCategory(\VisualImmersion\AdminBundle\Entity\SubCategory $subCategory)
    {
        $this->subCategories[] = $subCategory;
        $subCategory->setPostCategory($this);
    }

    /**
     * Get subCategories
     *
     * @return \Doctrine\Common\Collections\ArrayCollection()
     */
    public function getSubCategories()
    {
        return $this->subCategories;
    }

    /**
     * Set subCategories
     *
     * @param \Doctrine\Common\Collections\ArrayCollection $subCategories
     */
    public function setSubCategories(\Doctrine\Common\Collections\ArrayCollection $subCategories)
    {
        foreach ($subCategories as $subCategory) {
             $subCategory->setPostCategory($this);
        }

        $this->subCategories = $subCategories;
    }

    /**
     * Remove subCategory
     *
     * @param \VisualImmersion\AdminBundle\Entity\SubCategory $subCategory
     */
    public function removeSubCategory(\VisualImmersion\AdminBundle\Entity\SubCategory $subCategory)
    {
        $this->subCategories->removeElement($subCategory);
    }
}

我想这可能就是问题所在

您具有以下
@ManyToOne
关系:

/**
 * @ORM\ManyToOne(targetEntity="\VisualImmersion\AdminBundle\Entity\PostCategory", cascade={"remove", "persist"}, inversedBy="subCategories")
 * @ORM\JoinColumn(referencedColumnName="ID")
 */
private $postCategory;
。。。但关系双方都不知道外键列的名称。试着这样改变它:

@ORM\JoinColumn(name="postCategory_id", referencedColumnName="ID")

为什么不尝试使用ORM创建实体? 这也将有助于创建数据库。

我找到了一个解决方案:

/**
     * Edits an existing PostCategory entity.
     *
     * @Route("/update/{id}", name="postcategory_update")
     * @Method("PUT")
     * @Template("VisualImmersionAdminBundle:PostCategory:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {

        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('VisualImmersionAdminBundle:PostCategory')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find PostCategory entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new PostCategoryType(), $entity);

        $editForm->submit($request);
        if ($editForm->isValid()) {
            foreach ($entity->getSubCategories() as $subCategory)
            {
                $subCategory->setPostCategory($entity);
                $em->persist($subCategory);
            }
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('postcategory_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

我不确定这是不是最好的解决办法。必须实际更改控制器。我宁愿只为这些东西修改实体。你有更好的主意吗?

奇怪。你能给我们看一下控制器代码吗?@jperovic是的,控制器是在编辑时添加的。我在子类别manytone ORM中添加了nullable=false来测试它。我有这个错误:“执行'INSERT INTO post_category_subcategory(name,postCategory_id)'值(?,)'时发生异常,参数为[“Web”,null]:SQLSTATE[23000]:完整性约束冲突:1048列'postCategory_id'不能为null”。也许这有助于解决问题?事实上,你最后的评论帮了大忙我已经为您的问题添加了可能的解决方案…您好,不幸的是,此解决方案似乎没有更好的效果…:也许我们应该看看表格的侧面?我觉得Subcategory类型无法恢复实体后类别。我可能错了,但我不知道该去哪里找。。。你觉得怎么样?对不起,我不太明白:我不是已经明白了吗?
<?php

namespace VisualImmersion\AdminBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use VisualImmersion\AdminBundle\Entity\SubCategory;
use VisualImmersion\AdminBundle\Form\SubCategoryType;

/**
 * SubCategory controller.
 *
 * @Route("/subcategory")
 */
class SubCategoryController extends Controller
{

    /**
     * Lists all SubCategory entities.
     *
     * @Route("/", name="subcategory")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('VisualImmersionAdminBundle:SubCategory')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new SubCategory entity.
     *
     * @Route("/", name="subcategory_create")
     * @Method("POST")
     * @Template("VisualImmersionAdminBundle:SubCategory:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity  = new SubCategory();
        $form = $this->createForm(new SubCategoryType(), $entity);
        $form->submit($request);

        $logger = $this->get('logger');
        $logger->info('Nous sommes dans le Create Action de SubCategory');

        if ($form->isValid()) {
            $logger->info('Le formulaire semble valide dans le Create Action de SubCategory');
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('subcategory_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Displays a form to create a new SubCategory entity.
     *
     * @Route("/new", name="subcategory_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $logger = $this->get('logger');
        $logger->info('Nous sommes dans le New Action de SubCategory');
        $entity = new SubCategory();
        $form   = $this->createForm(new SubCategoryType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a SubCategory entity.
     *
     * @Route("/{id}", name="subcategory_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('VisualImmersionAdminBundle:SubCategory')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find SubCategory entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing SubCategory entity.
     *
     * @Route("/{id}/edit", name="subcategory_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('VisualImmersionAdminBundle:SubCategory')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find SubCategory entity.');
        }

        $editForm = $this->createForm(new SubCategoryType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing SubCategory entity.
     *
     * @Route("/{id}", name="subcategory_update")
     * @Method("PUT")
     * @Template("VisualImmersionAdminBundle:SubCategory:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('VisualImmersionAdminBundle:SubCategory')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find SubCategory entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new SubCategoryType(), $entity);
        $editForm->submit($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('subcategory_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a SubCategory entity.
     *
     * @Route("/{id}", name="subcategory_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->submit($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('VisualImmersionAdminBundle:SubCategory')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find SubCategory entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('subcategory'));
    }

    /**
     * Creates a form to delete a SubCategory entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}
/**
 * @ORM\ManyToOne(targetEntity="\VisualImmersion\AdminBundle\Entity\PostCategory", cascade={"remove", "persist"}, inversedBy="subCategories")
 * @ORM\JoinColumn(referencedColumnName="ID")
 */
private $postCategory;
@ORM\JoinColumn(name="postCategory_id", referencedColumnName="ID")
/**
     * Edits an existing PostCategory entity.
     *
     * @Route("/update/{id}", name="postcategory_update")
     * @Method("PUT")
     * @Template("VisualImmersionAdminBundle:PostCategory:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {

        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('VisualImmersionAdminBundle:PostCategory')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find PostCategory entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new PostCategoryType(), $entity);

        $editForm->submit($request);
        if ($editForm->isValid()) {
            foreach ($entity->getSubCategories() as $subCategory)
            {
                $subCategory->setPostCategory($entity);
                $em->persist($subCategory);
            }
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('postcategory_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }