我在两个实体之间有这种OneToMany关系:Sculpture
( 1 )和Image
( n )。我的目标是查询将Sculptures
。 Image
设置为featured
的所有0
。如果Sculpture
至少有一个Image
具有featured = 1
,则查询不应该检索它(按照设计,雕刻中只能显示一个图像)。
以下是生成的表格:
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`);
我尝试使用此Repository方法查询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();
}
}
并使用此Repository方法查询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
。
有什么想法吗?
谢谢!
答案 0 :(得分:1)
这样的事情:
$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();
我没有检查任何语法,但两种方法都可以正常工作。