当我执行查询时,它看起来像这样:
SELECT p FROM AppBundle\Entity\Shrubs p
WHERE p.botanicalname LIKE :botanicalname
AND p.commonname LIKE :commonname
AND p.borderlinehardy = :x
ORDER BY p.commonname ASC
但我希望x周围有引号。在查询中,我有这样的特定行:
andWhere("p.$key = :x")
但如果我在x周围添加单引号,我会得到"无效的参数编号"错误。如何在不得到错误的情况下在x周围加上引号?
编辑:我的整个查询如下:
$shrubs = $query
->where($query->expr()->like('p.botanicalname', ':botanicalname'))
->setParameter('botanicalname', '%' . $botanicalname . '%')
->andwhere($query->expr()->like('p.commonname', ':commonname'))
->setParameter('commonname', '%' . $commonname . '%')
->orderBy('p.commonname', 'ASC');
$checkfor = array("wetsoil"=>"Tolerates Wet Soil",
"borderlinehardy"=>"Borderline Hardy",
"moistsoil"=>"Prefers Moist Soil",
"peatysoil"=>"Prefers Peaty Soil",
"welldrainedsoil"=>"Prefers Well-drained Soil",
"drought"=>"Tolerates Drought",
"claysoil"=>"Tolerates Clay Soil",
"sandysoil"=>"Prefers Sandy Soil",
"loamsoil"=>"Prefers Loam Soil",
"infertilesoil"=>"Tolerates Infertile Soil",
"richsoil"=>"Prefers Rich Soil",
"compactedsoil"=>"Tolerates Compacted Soil",
"cityconditions"=>"Tolerates City Conditions",
"pollution"=>"Tolerates Pollution",
"salt"=>"Tolerates Salt Conditions",
"windy"=>"Tolerates Windy Conditions",
"shade"=>"Prefers Shade",
"partshade"=>"Prefers Part Shade",
"fullsun"=>"Prefers Full Sun");
reset($checkfor);
foreach ($checkfor as $key => $value) {
if (${$key} == "x") {
$shrubs = $query->andWhere("p.$key = ':x'")
->setParameter('x', $key)
->getQuery()
->getResult();
}
}
答案 0 :(得分:1)
为每次通话构建空洞查询
$checkfor = array("wetsoil"=>"Tolerates Wet Soil",
"borderlinehardy"=>"Borderline Hardy",
"moistsoil"=>"Prefers Moist Soil",
"peatysoil"=>"Prefers Peaty Soil",
"welldrainedsoil"=>"Prefers Well-drained Soil",
"drought"=>"Tolerates Drought",
"claysoil"=>"Tolerates Clay Soil",
"sandysoil"=>"Prefers Sandy Soil",
"loamsoil"=>"Prefers Loam Soil",
"infertilesoil"=>"Tolerates Infertile Soil",
"richsoil"=>"Prefers Rich Soil",
"compactedsoil"=>"Tolerates Compacted Soil",
"cityconditions"=>"Tolerates City Conditions",
"pollution"=>"Tolerates Pollution",
"salt"=>"Tolerates Salt Conditions",
"windy"=>"Tolerates Windy Conditions",
"shade"=>"Prefers Shade",
"partshade"=>"Prefers Part Shade",
"fullsun"=>"Prefers Full Sun");
reset($checkfor);
foreach ($checkfor as $key => $value) {
if (${$key} == "x") {
//create for each call a full query ,
//maybe you have not $this, then chnage it,
//but get a new instacne
$query = $this->entityManager->createQueryBuilder();
//create
$shrubs = $query
->where($query->expr()->like('p.botanicalname', ':botanicalname'))
->setParameter('botanicalname', '%' . $botanicalname . '%')
->andwhere($query->expr()->like('p.commonname', ':commonname'))
->setParameter('commonname', '%' . $commonname . '%')
->andWhere("p.$key = :$key")
->setParameter($key, $key)
->orderBy('p.commonname', 'ASC')
->getQuery()
->getResult();
}
}