简体   繁体   中英

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.

Firstly, IMHO you need change in class Note inversedBy to "notes". Also be sure your code looks like http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#many-to-many-bidirectional

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']);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM