得到上周用户连接的数量(symfony - sql)

时间:2017-05-15 23:40:00

标签: sql symfony

我想知道从当天开始的上周记录的用户数量,这就是我尝试使用此功能的原因:

class UserRepository extends EntityRepository
{
    public function findNumberLastWeek(){

    $dql = "SELECT count(p) FROM UserBundle:User p WHERE p.lastLogin >= 'DATEADD(day,-7, GETDATE())'";
    return $this->getEntityManager()
        ->createQuery($dql)
        ->getSingleScalarResult();

}

但不起作用:(

2 个答案:

答案 0 :(得分:1)

我用它在我的应用程序中做了类似的功能(计算最后一天连接的用户):

   /**
     * Get the number of users which were connected between two dates
     * @param startDate $
     * @param endDate $
     * @return array
     */
    public function countUsersConnectedBetweenDate($startDate, $endDate) {
        $qb = $this->createQueryBuilder('u');
        $qb
            ->select('COUNT(u) as numberConnectedUsersLastDay')
            ->where('u.lastLogin BETWEEN :startDate AND :endDate')
            ->setParameter("startDate", $startDate)
            ->setParameter("endDate", $endDate);

        return $qb->getQuery()->getSingleScalarResult();
    }

并且在控制器中(它只是为了获得最后一天的连接):

$em = $this->getDoctrine()->getManager();
        $startYesterday = new \DateTime();
        $startYesterday->modify('yesterday');
        $endYesterday = new \DateTime();
        $endYesterday->modify('1 second ago');

        $countConnectedUsersLastDay = $em->getRepository(User::class)->countUsersConnectedLastDay($startYesterday, $endYesterday);

你可以调整两个日期以匹配你想要的,我还没有测试过,但你可以试试这样的:

$em = $this->getDoctrine()->getManager();
        $lastWeek = new \DateTime();
        $lastWeek->modify('-1 week');
        $now = new \DateTime();

        $countConnectedUsersLastDay = $em->getRepository(User::class)->countUsersConnectedLastDay($lastWeek, $now);

我希望这会对你有帮助。

答案 1 :(得分:0)

  1. lastLogin应为DATE类型
  2. 请尝试以下方法:p.lastLogin< = DATE_ADD(CURRENT_DATE(), - 7,'day')