0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Doctrine QueryBuilderでMenyToMenyリレーションの検索

Posted at

symfonyで例えば以下のエンティティがあったとき、タグに属する記事を取得する

class Tag
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=32)
     */
    private $name;
}
class Entry
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=32)
     */
    private $title;

    /**
     * @ORM\ManyToMany(targetEntity=Tag::class)
     */
    private $Tag;
}

ManyToManyでリレーションされているのでDQLでは

$qb
    ->andWhere(':tag MEMBER OF a.Tag')
    ->setParameter('tag', $tag)
;

の様になる。

複数のタグで検索するには?

調べてみたけど出てこなかったので試行錯誤した結果以下でいけた

$qb
    ->andWhere(':tags MEMBER OF a.Tag')
    ->setParameter('tags', [$tag1, $tag2])
;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?