mysql - Symfony2 - 如何在 Doctrine 中使用一种形式将值插入到两个不同的表中?

标签 mysql symfony doctrine-orm doctrine

我确信之前已经有人问过这个问题,但我发现很难找到适合我的确切问题的解决方案,因此我希望有人可以帮助我。

基本上,我有两张表,一张名为“pet”,一张名为“customer_pet”。这两个表是链接的,以便我可以将宠物分配给特定的人(客户)。但是我发现,如果我将客户 ID 添加到表单中(这不是 pet 表中的字段),它不会保留任何内容。我认为我在 Doctrine 中遇到了不同类型的表和列关联的困难。

在我的宠物实体中,我有以下内容:

/**
 * @var integer
 *
 * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Oc49Customer", inversedBy="pet", cascade={"persist"})
 * @ORM\JoinTable(name="customer_pet",
 *   joinColumns={
 *     @ORM\JoinColumn(name="customer_id", referencedColumnName="id")
 *   },
 *   inverseJoinColumns={
 *     @ORM\JoinColumn(name="pet_id", referencedColumnName="id")
 *   }
 * )
 */
private $customer_id;

但我不确定如何将其映射回我的 customer_pet 实体中。 customer_pet 表仅包含 pet_id 和 customer_id。 pet_id 是在添加宠物时生成的,并且 customer_id 通过表单中的隐藏字段传递。

我对 Doctrine 中的表关联不太熟悉,因此我们将不胜感激。如果有人需要任何其他代码片段,请询问。

这是我的 addPet() 方法:

/**
     * Add pet
     *
     * @param \AppBundle\Entity\Pet $pet
     * @return Customer
     */
    public function addPet(\AppBundle\Entity\Pet $pet)
    {
        $this->pet[] = $pet;

        return $this;
    }

提前谢谢您 迈克尔

最佳答案

1)声明所有表。 2)创建表格。 3)发送到多个表。 4)保存数据。

use AppBundle\Entity\site;
use AppBundle\Entity\nba;

1)声明所有表。

 $site = new site;
 $nba = new nba;

2)创建表单

$form = $this->createFormBuilder($site)




    ->add('site_id', IntegerType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
    ->add('category', ChoiceType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px'), 'choices' => $output))
    ->add('team', ChoiceType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px'), 'choices' => $nbat))

3)插入到多个表中。

        $site_id = $form['site_id']->getData();
        $category = $form['category']->getData();
        $team = $form['team']->getData();




        $site->setSiteId($site_id);
        $site->setCategory($category);
        $nba->setWinner($team);

4)保存数据

            $em = $this->getDoctrine()->getManager();
            $em->persist($site);
            $em->persist($nba);
            $em->flush();

关于mysql - Symfony2 - 如何在 Doctrine 中使用一种形式将值插入到两个不同的表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31970045/

相关文章:

php - Symfony2 + Doctrine2 SQL 完整性违规 : Nullable field can't be null?

php - Symfony-传递后参数返回相同

entity - 如何在不知道其名称的情况下获取 Doctrine2 实体标识符

php - 学说查询不同的相关实体

mysql - DISTINCT 是否总是会为相同的 SQL 返回相同顺序的值?

php - Mysql变量不能通过php工作

php - 在 PHP 中从 MySQL 中提取 BLOB 图像数据

MySQL 对分组 (GROUP BY) 结果使用 ORDER BY

php - Symfony 或其他东西在执行测试时与登录用户混淆

Symfony 2 FOSUserBundle 与产品表的关系