【发布时间】:2015-08-19 04:57:49
【问题描述】:
我在两个实体之间有这种 OneToMany 关系:Sculpture(1) 和 Image(n)。我的目标是查询所有Image.featured 设置为0 的Sculptures。如果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`);
我尝试使用此存储库方法查询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();
}
}
但是当我只想要那些没有特色的Image时,这些都返回Sculptures。
有什么想法吗?
谢谢!
【问题讨论】:
-
我认为,如果您可以包含可以为您提供所需结果的查询,这将有所帮助(至少对我个人而言)。
-
@TimBiegeleisen:您的意思是原始 SQL 查询?不幸的是还没弄明白。
-
嗯,在我看来,您最好先解决这个问题,然后再尝试使用位于数据库顶部的框架。
-
@TimBiegeleisen:是的,我正在研究它,但同时我想问一下。
-
问这个问题没有错。我刚刚投票给你以提供帮助:-)
标签: php mysql symfony doctrine-orm query-builder