【问题标题】:Doctrine delete the oldest entry教义删除最旧的条目
【发布时间】:2016-04-27 12:02:30
【问题描述】:

我有一个 MongoDb 文档,其中包含 3 个字段 messageauthorsendAt,我创建了一个查询构建器来计算此文档上的所有数据库条目,如果有超过 20 个条目,我正在尝试删除最旧的。

sendAt 是发送消息时的当前日期时间 ("sendAt" : ISODate("2016-01-21T08:53:00Z"))

我有一个未完成的查询生成器

public function deleteOldestMessage()
{
    return $this->createQueryBuilder()
        ->delete('m')
        ->from('Messages', 'm')
        ->where('m.sendAt = ')
        ->execute();
}

但我真的不知道我应该在where 条件上添加什么。 我也许应该订购DESC sendAt 字段并删除列表中的第一个?

如何告诉查询生成器删除最旧的?

谢谢,

【问题讨论】:

    标签: php mongodb symfony orm doctrine-orm


    【解决方案1】:

    你需要先选择最旧的,然后你可以像这样删除它:

        $qb->select('m')
       ->from('Messages', 'm')
       ->orderBy('m.sendAt', 'DESC'); 
       $messages = $qb->getResult();
    

        if(count($messages) >= 20){
            //get the first element of array which is the oldest one
            $lastMessage = current($messages); 
            $em->remove($lastMessage);
        }
    

    【讨论】:

    • more than 20 entries怎么样
    【解决方案2】:

    您使用 sql 查询构建器选项而不是 mongodb。

    return $this->createQueryBuilder()
        ->remove()
        ->sort('sendAt', 'asc')
        ->getQuery()
        ->getSingleResult()
        ->execute();
    

    【讨论】:

    • more than 20 entries怎么样
    • 你说你有那个查询。先查询count,超过20再查询。
    • 是的,我只在条目超过 20 个时才调用此查询
    • 有了你的回答我得到这个错误Iterator would not be returned for query type: 6
    • 所以是的,您应该使用查询来查找最新的 id,然后像下面的答案一样将其删除。
    【解决方案3】:

    你可以试试这样的:

    $qb = $em->createQueryBuilder();
    $messages = $qb->select('m')
        ->from('Messages', 'm')
        ->orderBy('m.sendAt', 'ASC')
        ->getQuery()
        ->getResult()
    ;
    // You will receive array where in the top will be the oldest message.
    if (count($messages) > 20) {
        // And in your desired case, you can remove just one oldest message.
        $messageToDelete = array_shift($messages);
        $em->remove($lastMessage);
        $em->flush();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      相关资源
      最近更新 更多