我有这个表结构:
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 的实体。
学说查询构建器是否有可能实现这一目标?我尝试使用 groupBy,但这不起作用,因为使用 groupBy 时 orderBy 对结果没有影响。
谢谢!
最佳答案
您可以按DESC
排序并告诉 Doctrine 为 return max 一个结果
,例如:
$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();
希望对你有帮助
关于mysql - Doctrine - QueryBuilder - 获得结果中最年轻的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50569878/