Search code examples
symfonymany-to-manydql

ManyToMany relation with DQL query


On my website I have Users and Formations. I want that User can add Formations to their favorites. SO I did a ManyToMany relation on my User:

/**
     * Many User have Many Phonenumbers.
     * @ManyToMany(targetEntity="Formation")
     * @JoinTable(name="users_favorites",
     *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="formation_id", referencedColumnName="id", unique=true)}
     *      )
     */
    private $favorites;

It created users_favorites in my BDD, with the ids of the user and formation. Now I'm trying to query on this, I want to get all the Formations with the users that added this formation to their favorites. Here's what I tried:

public function findAllWithFormation(){
        return $this->createQueryBuilder('formation')
            ->leftJoin('formation.favorites', 'user')
            ->addSelect('formation')
            ->addSelect('user')
            ->getQuery()
            ->getOneOrNullResult()
            ;
    }

But I get this error:

[Semantical Error] line 0, col 100 near 'user': Error: Class App\Entity\Formation has no association named favorites

I don't know how to use the user_favorites table to make it work. thanks


Solution

  • I would recomend adding in your entity the name annotation.

    @ORM\Table(name="formation")
    

    That way the query build will know to what entity you are refering.

    Hope this helps, stay safe.