我有这个表结构:
CREATE TABLE `inventory_item` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`articleID` int(11) NOT NULL,
`quantity` int(11) NOT NULL,
`date` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
我有这个问题:
$rows = $this->getModelManager()->createQueryBuilder()
->select('ii')
->from(InventoryItem::class, 'ii')
->where('ii.articleId IN (:articleIds)')
->andWhere('ii.quantity > 0')
->orderBy('ii.date', 'ASC')
->setParameter('articleIds', $articleIds )
->getQuery()
->getResult();
在数据库中,我可以拥有如下所示的实体:
ID | ArticleID | Quantity | Date
1 | 100 | 10 | 2018-08-31
2 | 200 | 20 | 2018-07-31
3 | 100 | 40 | 2018-05-31
现在,当查询中的$ articleIds为100时,我想要输出200:
ID | ArticleID | Quantity | Date
2 | 200 | 20 | 2018-07-31
3 | 100 | 40 | 2018-05-31
因此,当ArticleID相等时,查询应仅返回具有最年轻日期的实体,但也应返回具有ArticleId = 200的实体。
在doctrine查询构建器中是否有可能实现此目的?我尝试使用groupBy,但这不起作用,因为orderBy在使用groupBy时对结果没有影响。
谢谢!
答案 0 :(得分:0)
您可以按DESC
排序并告诉Doctrine return max one result
,例如:
$query = $this->getModelManager()->createQueryBuilder()
->select('ii')
->from(InventoryItem::class, 'ii')
->where('ii.articleId IN (:articleIds)')
->andWhere('ii.quantity > 0')
->orderBy('ii.date', 'DESC')
->setParameter('articleIds', $articleIds )
->getQuery();
$result = $query
->setMaxResults(1)
->getResult();
希望这个帮助
答案 1 :(得分:0)
要根据每篇文章的日期属性获取最旧的行,您可以使用与您的实体的自联接,在DQL中它可以表示为
SELECT a
FROM YourBundle\Entity\InventoryItem a
LEFT JOIN YourBundle\Entity\InventoryItem b
WITH a.articleId = b.articleId
AND a.date > b.date
WHERE b.articleId IS NULL
ORDER BY a.date DESC
使用查询构建器,您可以将其重写为
$DM = $this->get( 'Doctrine' )->getManager();
$repo = $DM->getRepository( 'YourBundle\Entity\InventoryItem' );
$results = $repo->createQueryBuilder( 'a' )
->select( 'a' )
->leftJoin( 'YourBundle\Entity\InventoryItem', 'b', 'WITH', 'a.articleId = b.articleId AND a.date > b.date' )
->where( 'b.articleId IS NULL' )
->orderBy( 'a.date','DESC' )
->getQuery()
->getResult();