我想使用Doctrines QueryBuilder创建查询。
用户可以选择将通过选中或取消选中HTML表单中的复选框来搜索的数据库字段。这就是$_POST contains 'filters'
和“喜欢”的原因。
$_POST['filters']
看起来像这样:
array(2) { [0]=> string(4) "rack" [1]=> string(5) "shelf" }
我正在尝试获得以下查询结果
SELECT * FROM `inventories` WHERE (`rack` OR `shelf` LIKE '%01%') AND `checkedOutAt` IS NULL ORDER BY `lastChangedAt`
我在版本2.5.5中使用Doctrine,在版本7中使用PHP。我的控制器如下所示:
public function searchAction()
{
$filters = array();
$em = $this->getEntityManager();
$vendors = $em->getRepository('Entities\Vendor')->findAll();
if ($_POST)
{
$filters = $_POST['filters'];
$like = trim($_POST['like']);
$inventories = $em
->getRepository('Entities\Inventory')
->findInventoriesBySearch($like, $filters)
;
$this->addContext('like', $like);
}
else
{
$inventories = $em
->getRepository('Entities\Inventory')
->findInventories()
;
}
$count = count($inventories);
$this->addContext('filters', $filters);
$this->addContext('vendors', $vendors);
$this->addContext('inventories', $inventories);
$this->addContext('count', $count);
$this->setTemplate('inventoryAction');
}
然后是相应的存储库(“ findInventories()”存储库功能可以正常工作):
public function findInventoriesBySearch($like, $filters)
{
$em = $this->getEntityManager();
$orExpr = $qb->expr()->orX();
foreach ($filters as $filter)
{
$orExpr->add($qb->expr()->like($filter, $like));
}
$qb ->andWhere('i.checkedOutAt is NULL');
$qb->setParameter('like', '%' . $like . '%');
$qb->select('i')->where($orExpr)->addOrderBy('i.lastChangedAt', 'DESC');
return $qb->getQuery()->getResult();
}
运行脚本时,我收到以下错误消息:
致命错误:未捕获的学说\ ORM \ Query \ QueryException:SELECT i 机架LIKE 01 OR货架LIKE 01 ORDER BY i.lastChangedAt DESC in ... /供应商/主义/orm/lib/Doctrine/ORM/Query/QueryException.php:41 堆栈跟踪:#0 ... /供应商/主义/orm/lib/Doctrine/ORM/Query/Parser.php(483): 主义\ ORM \ Query \ QueryException :: dqlError('SELECT i WHERE ...')#1 ... /供应商/主义/orm/lib/Doctrine/ORM/Query/Parser.php(971): Doctrine \ ORM \ Query \ Parser-> semanticalError('line 0,col 15 ...', 阵列)#2 ... /供应商/主义/orm/lib/Doctrine/ORM/Query/Parser.php(1702): 主义\ ORM \ Query \ Parser-> AbstractSchemaName()#3 ... /供应商/主义/orm/lib/Doctrine/ORM/Query/Parser.php(1557): Doctrine \ ORM \ Query \ Parser-> RangeVariableDeclaration()#4 ... /供应商/主义/orm/lib/Doctrine/ORM/Query/Parser.php(1292): 中的Doctrine \ ORM \ Query \ Parser-> IdentificationVariableDeclaration() ... / vendor / doctrine / orm / lib / Doctrine / ORM / Query / QueryException.php在 第63
行
答案 0 :(得分:0)
尝试检查并更改它。
(仅是一个建议)请勿与$_POST
/请求类型/访问权限等一起使用。通过“您的方式”。使用带有类型提示的Request
,例如:
public function searchAction(Request $request){
if ($request->isMethod('POST')) {
$filters = $request->request->get('filters');
//.....
}else{
}
}
猜猜,这里存在问题:
//...
foreach ($filters as $filter)
{
$filter = 'i.'.$filter; // <== 'i.rack','i.shelf', so on
$orExpr->add($qb->expr()->like($filter, $like));
}