如何在Shopware 5.6中集成DateTimeInterface到Doctrine DBAL查询构建器
解决Shopware 5.6插件中DateTimeInterface日期筛选预购数据的问题
1. 正确接收前端日期输入
Shopware 5.6基于Symfony 2.8,后端接收日期参数时,直接从Request对象获取字符串后转换为DateTimeInterface即可,避免类型不匹配导致的筛选失效:
// 在统计模块控制器方法中 use Symfony\Component\HttpFoundation\Request; public function preorderStatsAction(Request $request) { // 获取前端传入的开始/结束日期(假设表单字段名为startDate、endDate) $startDateStr = $request->get('startDate'); $endDateStr = $request->get('endDate'); // 转换为DateTime对象,兼容DateTimeInterface $startDate = $startDateStr ? new \DateTime($startDateStr) : null; $endDate = $endDateStr ? new \DateTime($endDateStr) : null; // 传入查询逻辑获取数据 $preorders = $this->getPreordersByDateRange($startDate, $endDate); // 后续模板渲染等逻辑... }
2. 构建日期筛选的SQL查询
由于ps.order_date是YYYY-MM-DD格式字段,需确保查询条件与字段格式完全匹配,以下是两种可靠实现方式:
方式一:手动格式化日期字符串(兼容字符串/Date类型字段)
直接将DateTime对象格式化为YYYY-MM-DD字符串,与数据库字段格式对齐:
private function getPreordersByDateRange(?\DateTimeInterface $startDate, ?\DateTimeInterface $endDate) { $qb = $this->container->get('dbal_connection')->createQueryBuilder(); $qb->select('ps.product_id', 'SUM(ps.quantity) as preorder_quantity', 'SUM(ps.amount) as preorder_amount') ->from('s_plugin_preorder', 'ps') // 替换为你的预购表名 ->where('ps.status = :pendingStatus') ->setParameter('pendingStatus', '待发货'); // 替换为实际待发货状态值 // 添加开始日期筛选 if ($startDate) { $qb->andWhere('ps.order_date >= :startDate') ->setParameter('startDate', $startDate->format('Y-m-d')); } // 添加结束日期筛选 if ($endDate) { $qb->andWhere('ps.order_date <= :endDate') ->setParameter('endDate', $endDate->format('Y-m-d')); } $qb->groupBy('ps.product_id'); return $qb->execute()->fetchAll(); }
方式二:绑定DateTime对象(仅适用于DATE类型字段)
如果ps.order_date在数据库中是DATE类型,可直接传入DateTime对象,Shopware的DBAL会自动处理类型转换:
// 替换上述日期筛选代码块 if ($startDate) { $qb->andWhere('ps.order_date >= :startDate') ->setParameter('startDate', $startDate, \Doctrine\DBAL\Types\Types::DATE_MUTABLE); } if ($endDate) { $qb->andWhere('ps.order_date <= :endDate') ->setParameter('endDate', $endDate, \Doctrine\DBAL\Types\Types::DATE_MUTABLE); }
3. 空结果排查要点
- 检查前端传入的日期格式是否为
YYYY-MM-DD,非标准格式会导致DateTime转换失败,筛选条件不生效 - 确认数据库中
ps.order_date的实际存储格式,避免存在前导零缺失(如2024-5-3而非2024-05-03)的情况 - 验证待发货状态的条件值是否与数据库中
status字段的实际值匹配
内容的提问来源于stack exchange,提问作者mel_p
相关产品推荐
相关产品推荐

