如何在ManyToMany关系上访问LEFT JOIN的属性?

时间:2017-01-05 15:05:33

标签: symfony doctrine-orm dql

我有三个与各种关系相关联的实体:

-Band-
name
...
tours (ManyToMany with Tour)
shows (OneToMany with Show)

-Tour-
name
...
bands (ManyToMany with Band)
$shows(OneToMany with Show)

-Show-
date
...
band(ManyToOne with Band, nullable)
tour(ManyToOne with Tour, nullable)

我可以设置Show for Band(然后show_tour为NULL)以及Show for Tour(然后show_band为NULL)。

现在,我想获得给定Show的所有Band。我的DQL是这样的:

public function findAllShowsToComeFor($band)
{
    $date = new \DateTime('now');
    return $this->createQueryBuilder('s')
        ->leftJoin('s.band', 'band')
        ->where('band.id = :bid')
        ->setParameter('bid', $band->getId())
        ->leftJoin('s.tour', 'tour')
        ->where('tour.bands = :tid')
        ->setParameter('tid', $band->getId())
        ->andWhere('s.day >= :date')
        ->setParameter('date', $date->format('Y-m-d'))
        ->orderBy('s.day', 'ASC')
        ->getQuery()
        ->getResult();
}

当然,这会引发一个语法错误([语义错误]第0行,第92行'band =:tid':错误:无效的PathExpression。预期StateFieldPathExpression或SingleValuedAssociationField。),因为这些行:

->leftJoin('s.tour', 'tour')
->where('tour.bands = :tid')
->setParameter('tid', $band->getId())

我需要做类似的事情:

->leftJoin('s.tour', 'tour')
->where('tour.bands.id IN :tid')
->setParameter('tid', $band->getId())

但这是不可能的......

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

MEMBER OF,我相信你想要这样的东西:

$this->createQueryBuilder('s')
        ->leftJoin('s.tour', 'tour')
        ->where('s.band = :band OR :band MEMBER OF tour.bands')
        ->setParameter('band', $band)
        ->andWhere('s.day >= :date')
        ->setParameter('date', $date->format('Y-m-d'))
        ->orderBy('s.day', 'ASC')
        ->getQuery()
        ->getResult();

答案 1 :(得分:0)

如果您已经在Band上完成了乐队ID,则无需过滤Tour。

所以这会给你这个:

$this->createQueryBuilder('s')
    ->join('s.band', 'band')
    ->where('band.id = :bid')
    ->leftJoin('s.tour', 'tour')
    ->where('s.day >= :date')
    ->orderBy('s.day', 'ASC')
    ->setParameter('date', $date->format('Y-m-d'))
    ->setParameter('bid', $band->getId())
    ->getQuery()
    ->getResult();

有了这个,你将得到一个ShowC的ArrayCollection,如果你在它上面做了一个> getTour,你可能会有一个Tour(或NULL)。