我有两个实体之间的OneToMany关系:Sculpture(1)和Image(n)。我的目标是查询所有将所有Image.featured设置为0的Sculptures。如果一个Sculpture至少有一个具有featured = 1的Image,那么查询不应该检索它(通过设计,无论如何只能有一个雕塑图像)。
以下是生成的表:
CREATE TABLE IF NOT EXISTS `image` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sculpture_id` int(11) DEFAULT NULL,
`nom` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`featured` tinyint(1) NOT NULL,
`type` enum('mini','normal') COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_C53D045FB2720858` (`sculpture_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;和
CREATE TABLE IF NOT EXISTS `sculpture` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`titre` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`reference` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`largeur` int(11) NOT NULL,
`hauteur` int(11) NOT NULL,
`annee` varchar(4) COLLATE utf8_unicode_ci NOT NULL,
`matiere` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`active` tinyint(1) NOT NULL,
`creation` datetime NOT NULL,
`description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`hits` int(11) NOT NULL,
`taille` enum('xs','s','m','l','xl') COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;使用
ALTER TABLE `image`
ADD CONSTRAINT `FK_C53D045FB2720858` FOREIGN KEY (`sculpture_id`) REFERENCES `sculpture` (`id`);我尝试使用这个存储库方法查询Sculpture实体:
class SculptureRepository extends EntityRepository
{
public function findByFeatured($featured)
{
$query = $this->createQueryBuilder('s')
->leftJoin('AppBundle\Entity\Image', 'i', 'WITH', 'i.sculpture = s.id')
->where('i.featured = :featured')
->setParameter('featured', $featured)
->orderBy('s.id', 'DESC')
->groupBy('s')
->getQuery()
;
return $query->getResult();
}
}并使用此存储库方法查询Image实体:
class ImageRepository extends EntityRepository
{
public function findNoFeatured()
{
$query = $this->createQueryBuilder('i')
->where('i.featured = 0')
->groupBy('i.sculpture')
->getQuery();
return $query->getResult();
}
}但是,当我只想要那些没有功能的Sculptures时,它们会返回所有的Image。
有什么想法吗?
谢谢!
发布于 2015-08-19 05:23:06
就像这样:
$query = $this->createQueryBuilder('s, count(i.id) as featured_image_count')
->leftJoin('AppBundle\Entity\Image', 'i', 'WITH', 'i.sculpture = s.id')
->where('i.featured = :featured')
->setParameter('featured', 1)
->orderBy('s.id', 'DESC')
->groupBy('s')
->having('featured_image_count < 1')
->getQuery()
;或者,您可以使用一个子查询来获取所有特征为== 1的图像,然后您可以使用not in来消除所有这些雕塑,例如:
$qb = $this->createQueryBuilder();
$qb2 = $qb;
$qb2->select('i.sculptureId')->distinct(true)
->from('AppBundle\Entity\Image', 'i')
->where('i.featured = 1');
$qb = $this->createQueryBuilder();
$qb->select('s')
->from('AppBundle\Entity\Sculpture', 's')
->where($qb->expr()->notIn('s.id', $qb2->getDQL())
);
$result = $qb->getQuery()->getResult();我没有检查这些语法,但这两种方法都能正常工作。
https://stackoverflow.com/questions/32086846
复制相似问题