在Symfony 2

时间:2018-02-12 09:54:30

标签: php symfony doctrine-orm many-to-many symfony-2.8

我有两个实体之间的多对多关系:Agent&适应训练。 我在表单验证时遇到错误:

  

无法解析列的类型" id"班级   " CNAMTS \ RAVC \捆绑\实体\剂"

一开始,我的Agent和Habilitation $ id是$ ageId和$ habId,但我已经有了同样的错误。我曾尝试在两个实体中仅更改$ id,但我仍然遇到此错误。

当我执行doctrine:schema:validate

时也会出错
  

[Mapping] FAIL - 实体类' CNAMTS \ RAVC \ Bundle \ Entity \ Agent'   映射无效:

     
      
  • 引用的列名称' id'必须是目标实体类的主键列' CNAMTS \ RAVC \ Bundle \ Entity \ Agent'。
  •   
  • 引用的列名称' id'必须是目标实体类的主键列' CNAMTS \ RAVC \ Bundle \ Entity \ Habilitation'。

         

    [Doctrine \ DBAL \ Schema \ SchemaException]具有名称的表   ' valid_comptes.agent_j_habilitation'已存在。

  •   

我使用的是Symfony 2.8和Doctrine 2。

他是我的代码和BDD定义:

代理商:

/**
 * Agent
 *
 * @ORM\Table(name="agent")
 * @ORM\Entity(repositoryClass="...\...\Bundle\Repository\AgentRepository")
 */
class Agent
{
    /**
     * @var integer
     *
     * @ORM\Id
     * @ORM\Column(name="age_id", type="integer")
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="age_numero", type="string", length=5, nullable=true)
     */

    private $ageNumero;

    /**
     * @var string
     *
     * @ORM\Column(name="age_nom", type="string", length=100, nullable=true)
     */

    private $ageNom;

    /**
     * @var string
     *
     * @ORM\Column(name="age_prenom", type="string", length=100, nullable=true)
     */
    private $agePrenom;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Habilitation", inversedBy="agents")
     * @ORM\JoinTable(
     *     name="agent_j_habilitation",
     *     joinColumns={@ORM\JoinColumn(name="fk_hab_id", referencedColumnName="id", nullable=false)},
     *     inverseJoinColumns={@ORM\JoinColumn(name="fk_age_id", referencedColumnName="id", nullable=false)}
     * )
     *
     */
    private $habilitations;

    /**
     * Agent constructor.
     */
    public function __construct()
    {
        $this->habilitations = new ArrayCollection();
    }

    /**
     * @param Habilitation $habilitation
     */
    public function addHabilitation(Habilitation $habilitation)
    {
        $habilitation->addAgent($this);
        $this->habilitations[] = $habilitation;
    }
}

Habilitation:

/**
 * Habilitation
 *
 * @ORM\Table(name="habilitation")
 * @ORM\Entity
 * @ORM\Entity(repositoryClass="...\...\Bundle\Repository\HabilitationRepository")
 */
class Habilitation
{
    /**
     * @var integer
     *
     * @ORM\Id
     * @ORM\Column(name="hab_id", type="integer")
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="hab_libelle", type="string", length=50, nullable=true)
     */
    private $habLibelle;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Agent", mappedBy="habilitations")
     */
    private $agents;

    /**
     * Habilitation constructor.
     */
    public function __construct()
    {
        $this->agents = new ArrayCollection();
    }

    /**
     * @param Agent $agent
     */
    public function addAgent(Agent $agent)
    {
        $this->agents[] = $agent;
    }
}

AjoutUserType

class AjoutUserType extends AbstractType
{    
    /**
     * Constructor.
     *
     */
    public function __construct()
    {
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add('ageNumero', 'text', [
                'label' => 'Numéro'
            ])
            ->add('ageNom', 'text', [
                'label' => 'Nom'
            ])
            ->add('agePrenom', 'text', [
                'label' => 'Prénom'
            ])
            ->add('habilitations', EntityType::class, [
                'class' => 'RAVCBundle:Habilitation',
                'label' => 'Habilitation',
                'property' => 'habLibelle',
                'multiple' => true,
                'placeholder' => '-- Sélectionnez une habilitation --',
            ]);
    }



    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'data_class' => Agent::class
            ]
        );
    }
}

动作控制器:

   /**
     * @Route("/ajoutUser", name="ravc_ajoutUser")
     * @Method({"GET", "POST"})
     * @internal param Request $request
     */
    public function newAgentAction(Request $request)
    {
        $agent = new Agent();

        $form = $this->createForm(new AjoutUserType(), $agent);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($agent);
            $em->flush();
            $this->notification('L\'agent a été ajouté avec succès.');

            return $this->redirectToRoute('ravc_ajoutUser');
        }

        return $this->render('RAVCBundle:Admin:ajoutUser.html.twig', ['form' => $form->createView()]);
    }

表格定义:

CREATE TABLE `agent` (
  `age_id` int(11) NOT NULL AUTO_INCREMENT,
  `age_numero` varchar(6) DEFAULT NULL,
  `age_nom` varchar(100) DEFAULT NULL,
  `age_prenom` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`age_id`)
) ENGINE=InnoDB AUTO_INCREMENT=91 DEFAULT CHARSET=latin1;

CREATE TABLE `agent_j_habilitation` (
  `ajh_id` int(11) NOT NULL AUTO_INCREMENT,
  `fk_hab_id` int(11) NOT NULL,
  `fk_age_id` int(11) NOT NULL,
  PRIMARY KEY (`ajh_id`),
  KEY `ajh_fk_hab_id` (`fk_hab_id`),
  KEY `ajh_fk_age_id` (`fk_age_id`),
  CONSTRAINT `ajh_fk_age_id` FOREIGN KEY (`fk_age_id`) REFERENCES `agent` (`age_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ajh_fk_hab_id` FOREIGN KEY (`fk_hab_id`) REFERENCES `habilitation` (`hab_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=109 DEFAULT CHARSET=latin1;

-- ----------------------------
-- Table structure for habilitation
-- ----------------------------
DROP TABLE IF EXISTS `habilitation`;
CREATE TABLE `habilitation` (
  `hab_id` int(11) NOT NULL AUTO_INCREMENT,
  `hab_libelle` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`hab_id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=latin1;

1 个答案:

答案 0 :(得分:1)

教条注释应该反映真实的列名称(如模式验证的建议),对于第一个(joinColumn)你应该定义起始实体数据),所以试试这个:

/**
 * @var ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity="Habilitation", inversedBy="agents")
 * @ORM\JoinTable(
 *     name="agent_j_habilitation",
 *     joinColumns={@ORM\JoinColumn(name="fk_age_id", referencedColumnName="age_id", nullable=false)},
 *     inverseJoinColumns={@ORM\JoinColumn(name="fk_hab_id", referencedColumnName="hab_id", nullable=false)}
 * )
 *
 */
private $habilitations;

这应该修复doctrine:schema:validate命令

AjoutUserType 中,关系应该由CollectionType而不是EntityType

映射