document-querybuilder-get结果中最年轻的实体

pu82cl6c  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(253)

我有这个表结构:

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为100200时,我希望有以下输出:

ID | ArticleID | Quantity | Date
2  | 200       |     20    | 2018-07-31
3  | 100       |     40    | 2018-05-31

因此,当articleid等于时,查询应该只返回最年轻日期的实体,还应该返回articleid=200的实体。
条令查询生成器中是否有可能实现这一点?我用groupby试过,但这不起作用,因为使用groupby时orderby对结果没有影响。
谢谢!

slmsl1lt

slmsl1lt1#

你可以按 DESC 告诉条令让麦克斯回来 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();

希望这有帮助

odopli94

odopli942#

要根据每个项目的date属性获取最早的行,可以使用实体的自联接,在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();

条令查询语言获取每个组的最大/最新行数

相关问题