Symfony3 doctrine Many-to-Many column not found on select

Viewed 1196

I'm begginer with Symfony and Doctrine and I have a problem with a many-to-many relationship. I have the next two entities, relationated with many-to-many.

AppBundle/Entity/User.php

/**
* @ORM\ManyToMany(targetEntity="Team", mappedBy="user", cascade={"all"})
*
*/
private $team;

public function __construct()
{
    parent::__construct();

    $this->team = new \Doctrine\Common\Collections\ArrayCollection();
}

/**
 * Add team
 *
 * @param \AppBundle\Entity\Team $team
 *
 * @return User
 */
public function addTeam(\AppBundle\Entity\Team $team)
{
    $this->team[] = $team;

    return $this;
}

/**
 * Remove team
 *
 * @param \AppBundle\Entity\Team $team
 */
public function removeTeam(\AppBundle\Entity\Team $team)
{
    $this->team->removeElement($team);
}

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

AppBundle/Entity/Team.php

/**
* @ORM\ManyToMany(targetEntity="User", inversedBy="team", cascade={"persist"})
* @ORM\JoinTable(name="user_team")
*/
private $user;

public function __construct()
{

    $this->user = new \Doctrine\Common\Collections\ArrayCollection();
}

/**
 * Add user
 *
 * @param \AppBundle\Entity\User $user
 *
 * @return Team
 */
public function addUser(\AppBundle\Entity\User $user)
{
    $this->user[] = $user;

    return $this;
}

/**
 * Remove user
 *
 * @param \AppBundle\Entity\User $user
 */
public function removeUser(\AppBundle\Entity\User $user)
{
    $this->user->removeElement($user);
}

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

In my controller, I have the following code:

AppBundle/Controller/DefaultController.php

$em = $this->getDoctrine()->getManager();        
$em->getRepository('AppBundle:Team')->findBy(array('user'=>$usr));

And I have te next error:

An exception occurred while executing 'SELECT t0.id AS id_1, t0.name AS name_2, t0.description AS description_3, t0.active AS active_4, t0.date_add AS date_add_5, t0.date_modified AS date_modified_6 FROM team t0 WHERE user_team.user_id = ?' with params [2]:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_team.user_id' in 'where clause' 500 Internal Server Error - InvalidFieldNameException

What are i'm doing wrong?

The relation? The controller? Maybe everything?

Thank you :)

2 Answers

If you want to get users of a Team, use your getUser function on a Team object:

$em    = $this->getDoctrine()->getManager();
$team  = $em->getRepository('AppBundle:Team')->find( $aTeamId );

$users = $team->getUser();
Related