Symfony Doctrine 多对多关系:无法识别的字段

Symfony Doctrine ManyToMany Relationship : unrecognized field

我遇到了几天都无法解决的问题。

我有一个小组 table 和一个统计问题 table。

1 个统计问题 --> 几个组 1 组 --> 几个统计问题

我设置了多对多关系。

实体:

集团:

/**
 * Groupe
 *
 * @ORM\Table(name="groupe")
 * @ORM\Entity
 */
class Groupe
{
    ...
    /**
 * @ORM\ManyToMany(targetEntity="\PACES\StatistiqueBundle\Entity\StatistiqueQuestion", mappedBy="groupes",
 * cascade={"all"})
 */
private $statistiquesquestion;

....
}

统计问题:

/**
 * StatistiqueQuestion
 *
 * @ORM\Table(name="statistiquequestion")
 * @ORM\Entity
 */
class StatistiqueQuestion
{
   ...
   /**
 * @ORM\ManyToMany(targetEntity="\PACES\UserBundle\Entity\Groupe",inversedBy="statistiquesquestion" , cascade={"persist"})
 * @ORM\JoinColumn(name="groupe_id", referencedColumnName="id")
 */
private $groupes;

....
}

当我尝试查找 StatistiqueQuestion 对象时,出现此错误:

SQLSTATE[42S22]: Column not found: 1054 Unrecognized field 'statistiquequestion_groupe.groupe_id' in where clause

这是我获取对象的代码:

                    $statsQuestion[]=$em->getRepository( StatistiqueQuestion::class )->findOneBy( [ 'question'  => $colle,
                                                                                             'groupes' => $groupes
                                                                                           ] );

当我转储 $groupes 时,我得到了预期的对象数组。

也许你可以试试

php app/console doctrine:mapping:info

php app/console doctrine:schema:validate

如果数据库不同步,您可能需要 doctrine:schema:update(或者在您使用 Doctrine Migrations 的情况下生成迁移)

找到解决方案。

问题是 findBy 方法不允许获取具有多对多关系的对象。

解决方案:

   public function getStatColleForGroupes($colle, $groupes){
    $requete = $this->_em->createQuery('SELECT s
                                        FROM PACESStatistiqueBundle:StatistiqueColle s
                                        WHERE s.colle = :colle
                                        ');
    $requete->setParameters(array('colle'=>$colle));
    $resultats= $requete->getResult();


    foreach ($resultats as $resultat)
    {
        if ($groupes == $resultat->getGroupes()->toArray())
            return $resultat;
    }

    return null;
}

它不是最优的,但它是我找到的解决问题的唯一方法