我正在尝试为我的数据库构建过滤器。基于几个表单输入的值,我需要构造适当的查询。这是代码:
$qb = $em->createQueryBuilder();
$qb->select('c.title')
->from('Baza\BlogBundle\Entity\Conferences', 'c');
$conditions=array(
$qb->expr()->gt('c.title',$enquiry->getNaziv()) );//First condition
if ($enquiry->getKontakt()!=null) {
$conditions[] = $qb->expr()->lt('c.contactemail',$enquiry->getKontakt())}//Adding second, optional condition
$conditions = call_user_func_array(array($qb, 'andX'), $conditions);
$qb->where($conditions);
$query = $qb->getQuery();
当我运行这个时,我得到了以下例外:
警告:call_user_func_array()期望参数1是有效的回调,类'Doctrine \ ORM \ QueryBuilder'没有方法'andX'
*编辑在call_user_func_array()修改后,我收到以下错误:
QueryException:SELECT c.title FROM Baza \ BlogBundle \ Entity \ Conferences c WHERE c.title> ITRO和c.contactemail< somemail@yahoo.com
显然,查询格式不正确。我关注此帖:Doctrine DQL conditional query
有什么想法吗?
答案 0 :(得分:2)
我使用以下代码构建了动态查询:
$em = $this->getDoctrine()->getEntityManager();
$naziv = $enquiry->getNaziv();
$drzava=$enquiry->getDrzava();
$oblast=$enquiry->getOblast();
$grad=$enquiry->getGrad();
$provincija=$enquiry->getProvincija();
$kontakt=$enquiry->getKontakt();
$sajt=$enquiry->getSajt();
$testquery = "SELECT c.title FROM Baza\BlogBundle\Entity\Conferences c JOIN c.topicid t JOIN c.locationid l JOIN l.stateid s WHERE c.lh = :lh";
$testparam ['lh'] = $lh;
if ($kontakt != '') {
$testquery .= " and c.contactemail = :kontakt";
$testparam['kontakt'] = $kontakt;
}
if ($drzava != '') {
$testquery .= " and s.name = :drzava";
$testparam['drzava'] = $drzava;
}
if ($provincija != '') {
$testquery .= " and l.province = :provincija";
$testparam['provincija'] = $provincija;
}
if ($grad != '') {
$testquery .= " and l.city = :grad";
$testparam['grad'] = $grad;
}
if ($sajt != '') {
$testquery .= " and c.siteurl = :sajt";
$testparam['sajt'] = $sajt;
}
if ($oblast != '') {
$testquery .= " and t.name = :oblast";
$testparam['oblast'] = $oblast;
}
$query = $em->createQuery($testquery)->setParameters($testparam);
$result = $query->getResult();
答案 1 :(得分:0)
andx是expr()的函数,而不是查询构建器的函数:
$ conditions = call_user_func_array(array($ qb-> expr(),'andx'),$ conditions);
答案 2 :(得分:0)
关于你的编辑:
$qb = $em->createQueryBuilder();
$qb->select('c')
->from('Baza\BlogBundle\Entity\Conferences', 'c');
使用doctrine(作为ORM)来选择整个对象。你仍然可以在字段上的where子句。另外gt和lt字符串搜索不是真正适合sql的做法。如果信件不当,他们可能会产生奇怪的结果。
答案 3 :(得分:0)
几年后,这就是我的做法:
if (array_key_exists('phone', $filters)) {
$qb->andWhere('p.phone LIKE :phone')
->setParameter(':phone', '%' . $filters['phone'] . '%');
}
希望这对某人有帮助