Error when I try to make a ManyToMany relation in

2019-07-22 19:39发布

问题:

I want to make a ManyToMany relation in Doctrine with Symfony 2 between a group and an user : many users can be in many groups and many groups can have many users.

Then in my entities, i do this :

Groupe.php

/**
* Many Groups have Many clients.
* @ORM\ManyToMany(targetEntity="Utilisateurs\UtilisateursBundle\Entity\Client", mappedBy="groupe")
* @ORM\JoinTable(name="client_groupe")
*/
private $clients;

 /**
 * Get clients
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getClients()
{
    return $this->clients;
}

Client.php

/**
     * @ORM\ManyToMany(targetEntity="Ecommerce\EcommerceBundle\Entity\Groupe", inversedBy="clients")     
     * @ORM\JoinTable(name="client_groupe",
     *   joinColumns={@ORM\JoinColumn(name="client_id", referencedColumnName="id")},
     *   inverseJoinColumns={@ORM\JoinColumn(name="groupe_id", referencedColumnName="id")}
     * )

     */
    private $groupe;

but when I call the getClients() function on my entity $groupe, following error occured :

FROM client t0 WHERE client_groupe.groupe_id = ?' with params ["2"]:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'client_groupe.groupe_id' in 'where clause'

It doesn't add the client_groupe table in the from clause.

Someone can help me ?

回答1:

No need to add client_groupe table in from clause. Try after removing * @ORM\JoinTable(name="client_groupe") from Groupe.php. Have a look at following working example of ManyToMany relationship scenario.

Groupe.php

/**
* Many Groups have Many clients
* @ORM\ManyToMany(targetEntity="Utilisateurs\UtilisateursBundle\Entity\Client", mappedBy="groupe")
*/
private $clients;

Client.php

/**
 * @ORM\ManyToMany(targetEntity="Ecommerce\EcommerceBundle\Entity\Groupe", inversedBy="clients")     
 * @ORM\JoinTable(name="client_groupe",
 *   joinColumns={@ORM\JoinColumn(name="client_id", referencedColumnName="id")},
 *   inverseJoinColumns={@ORM\JoinColumn(name="groupe_id", referencedColumnName="id")}
 * )
 */
private $groupe;

client_id and groupe_id is fields of client_groupe table. Generate Getter and setter using doctrine command and update database using bin/console doctrine:schema:update --force command.