這篇文章主要介紹了Symfony2針對輸入時間進行查詢的方法,結合實例形式分析了Symfony2針對mysql及MongoDB的輸入時間進行轉換與查詢的相關操作技巧,需要的朋友可以參考下
本文實例講述了Symfony2針對輸入時間進行查詢的方法。分享給大家供大家參考,具體如下:
一般情況下:前端輸入一個時間,我們一般是先將時間修改成一個時間戳
strtotime — 將任何英文文字的日期時間描述解析為Unix 時間戳
例如:
##
$startTimestamp = strtotime($startDate); $endTimestamp = strtotime($endDate);
$start = date('Y-m-d 00:00:00', $startTimestamp); $end = date('Y-m-d 23:59:59', $endTimestamp);
1. 在MySQL中的使用
if(empty($startDate)) { throw new \Exception('起始时间不为空', BaseException::ERROR_CODE_ILLEGAL_PARAMETER); } if (empty($endDate)) { $endDate = $startDate; } $startTimestamp = strtotime($startDate); $endTimestamp = strtotime($endDate); if ($startTimestamp > $endTimestamp) { throw new \Exception('时间参数错误', BaseException::ERROR_CODE_ILLEGAL_PARAMETER); } if ($status == InventoryOrder::STATUS_SUBMITTED) { $index = 'i.submitTime'; } else if ($status == InventoryOrder::STATUS_UNSUBMITTED) { $index = 'i.createTime'; } else if (empty($status)) { $index = 'i.createTime'; } else { throw new \Exception('时间格式不正确', BaseException::ERROR_CODE_ILLEGAL_PARAMETER); } $sql = 'SELECT i FROM AppBundle:InventoryOrder i WHERE '; $sql .= $index; $sql .= ' BETWEEN :startDate AND :endDate '; $start = date('Y-m-d 00:00:00', $startTimestamp); $end = date('Y-m-d 23:59:59', $endTimestamp); $params['endDate'] = $end; $params['startDate'] = $start; if (!empty($status)) { $sql .= ' AND i.status = :status'; $params['status'] = $status; } $sql .=' ORDER By i.createTime DESC'; $query = $this->entityManager->createQuery($sql); $orderList = $query->setParameters($params)->getResult();
2. 在mongodb中的時間的輸入和查詢列子##在這裡面其實有兩個坑:
@ ->field('submit_time')->gt(new \DateTime($start)) ->field('submit_time')->lt(new \DateTime($end))
$query->field('status')->equals($status);
$data = array(); if (!isset($startDate)) { throw new \Exception("参数不正确", BaseException::ERROR_CODE_ILLEGAL_PARAMETER); } if (empty($endDate)) { $endDate = $startDate; } $startTimestamp = strtotime($startDate); $endTimestamp = strtotime($endDate); if ($startTimestamp > $endTimestamp) { throw new \Exception("参数不正确", BaseException::ERROR_CODE_ILLEGAL_PARAMETER); } $start = date('Y-m-d 00:00:00', $startTimestamp); $end = date('Y-m-d 23:59:59', $endTimestamp); $scanner = Order::FROM_TYPE_SCANNER; $query = $this->documentManager ->createQueryBuilder('AppBundle:Order') ->field('submit_time')->gt(new \DateTime($start)) ->field('submit_time')->lt(new \DateTime($end)) ->field('from_type')->equals("$scanner"); if (!empty($status) && in_array($status, array(Order::STATUS_CANCELLED, Order::STATUS_SUBMITTED))) { $status = $status + 0; $query->field('status')->equals($status); } else if (empty($status)) { $status = Order::STATUS_SUBMITTED + 0; $query->field('status')->equals($status); } else { throw new \Exception("参数不正确", BaseException::ERROR_CODE_ILLEGAL_PARAMETER); } $orderList = $query->sort('create_time', 'DESC') ->getQuery() ->execute();
以上是Symfony2輸入時間查詢的詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!