我有两个实体Person和Nursery,我和ManyToMany
之间有一个JoinTable
关系。我想做这2个SQL查询:
1)使用nursery_id
查找链接到托儿所的所有员工(= Person)select p.* from person p inner join nursery_staff ns on p.id = ns.staff_id inner join nursery n on ns.nursery_id = n.id where n.id=1 and p.nursery_staff_role <> 'MANAGER';
2)找到有staff_id的员工,并确保他与托儿所的托儿所相关联
select p.* from person p inner join nursery_staff ns on p.id = ns.staff_id inner join nursery n on ns.nursery_id = n.id where n.id=2 and p.id=4 and p.nursery_staff_role <> 'MANAGER';
为此我在PersonRepository中有这两个查询:
1)
public function findAllStaffLinkedToANursery($nursery_id)
{
$qb = $this->_em->createQueryBuilder();
$qb->select('p')
->from($this->_entityName, 'p')
->innerJoin('VSCrmBundle:Nursery', 'n')
->where('n.id = :id')
->andWhere('p.nurseryRole <> :profession')
->setParameters(array('id' => $nursery_id, 'profession' => 'MANAGER'));
return $qb->getQuery()->getResult();
}
2)
public function findOneByNurseryAndStaffId($nursery_id, $staff_id)
{
$qb = $this->_em->createQueryBuilder();
$qb->select('p')
->from($this->_entityName, 'p')
->innerJoin('VSCrmBundle:Nursery', 'n')
->where('p.id = :pid')
->andWhere('n.id = :nid')
->andWhere('p.nurseryRole <> :staffRole')
->setParameters(array(
'pid' => $staff_id,
'nid' => $nursery_id,
'staffRole' => 'MANAGER'
));
return $qb->getQuery()->getOneOrNullResult();
}
但是在这两种情况下,查询都不关心nursery_id,并且这使我的工作人员不再使用nursery_id。例如,id = 4的Person未与id = 2的托儿所链接,但此查询显示此人。
编辑: 我对dql查询有相同的结果:
php bin/console doctrine:query:dql "select p.email from VSCrmBundle:Person p inner join VSCrmBundle:Nursery n where n.id=2 and p.nurseryRole <> 'MANAGER'"
答案 0 :(得分:0)
也许这就是你加入幼儿园实体的方式。 尝试从Person实体属性加入它,如下所示:
public function findAllStaffLinkedToANursery($nursery_id)
{
$qb = $this->_em->createQueryBuilder();
$qb->select('p')
->from($this->_entityName, 'p')
->innerJoin('p.nursery', 'n')
->where('n.id = :id')
->andWhere('p.nurseryRole <> :profession')
->setParameters(array('id' => $nursery_id, 'profession' => 'MANAGER'));
return $qb->getQuery()->getResult();
}
这当然只有在Person具有属性苗圃并且使用Doctrine ORM映射时才有效。 如果存储库扩展了Doctrine \ ORM \ EntityRepository,您也可以简化它:
public function findAllStaffLinkedToANursery($nursery_id)
{
$qb = $this->createQueryBuilder('p');
$qb->innerJoin('p.nursery', 'n')
->where('n.id = :id')
->andWhere('p.nurseryRole <> :profession')
->setParameters(array('id' => $nursery_id, 'profession' => 'MANAGER'));
return $qb->getQuery()->getResult();
}
答案 1 :(得分:0)
好的,感谢Sepultura我的代码有效!我点了这个:
public function findAllStaffLinkedToANursery($nursery_id)
{
$qb = $this->createQueryBuilder('p');
$qb->innerJoin('p.nurseries', 'n')
->where('n.id = :id')
->andWhere('p.nurseryRole <> :profession')
->setParameters(array('id' => $nursery_id, 'profession' => 'MANAGER'));
return $qb->getQuery()->getResult();
}