Search code examples
phpsymfonydoctrine-ormtagsmany-to-many

Semantical Error with fetching associated data in many-to-many relation with symfony3


I have a simple app makes in symfony3. I try to fetch appropriate tags for my entities and I have a problem.

There is a part of my tag entity:

/**
 * Tag
 *
 * @ORM\Table(name="tag")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\TagRepository")
 */
class Tag
{
    .
    .
    .

    /**
     * @ORM\ManyToMany(targetEntity="Note", mappedBy="tags")
     */
    private $notes;

...and there is a part of note entity:

/**
 * Note
 *
 * @ORM\Table(name="note")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\NoteRepository")
 */
class Note
{
     .
     .
     .

    /**
     * @ORM\ManyToMany(targetEntity="Tag", inversedBy="notes", cascade={"persist"})
     * @ORM\JoinTable(name="notes_tags")
     */
    private $tags;

In my repository class I call:

if(!empty($data['tags'])) {
    $query->andWhere('n.tags = :tag')->setParameter('tag', 6);
}

...then results is:

[Semantical Error] line 0, col 46 near 'tags = :tag ORDER': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.

I'm really new in Symfony 2 and Doctrine so I need your help.


Solution

  • I found a solution, I have to use MEMBER OF clause:

        if(!empty($data['tags'])) {
            $query->andWhere(':tag MEMBER OF n.tags')->setParameter('tag', $data['tags']);
        }