Kristen Joseph-Delaffon Kristen Joseph-Delaffon - 2 months ago 26
PHP Question

Symfony Doctrine ManyToMany Relationship : unrecognized field

I came into a problem I can't solve for several days now.

I have a groupe table and a statistiquequestion table.

1 statistiquequestion --> several groupes
1 groupe --> several statistiquequestion

I set up a ManyToMany relationship.

Entities :

Groupe :

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

....
}


StatistiqueQuestion :

/**
* 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;

....
}


When I try to find a StatistiqueQuestion object, I have this error :

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


Here's my code to get the object :

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


When I dump $groupes, I get an array of objects as intended.

Answer

Found the solution.

Problem was that findBy method doesn't allow to get an object with a ManyToMany Relationship.

Solution :

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

It's not optimal but it's the only solution I found to my problem

Comments