我正在使用cakephp分页我正在使用2组复选框来过滤 materialtype 和场合所以我写了以下代码
public function index($category) {
if(!empty($this->params['url']['data']['filter']['materialtype']))
{
foreach ($this->params['url']['data']['filter']['materialtype'] as $v){
$conditions1[] ="(Product.materialtype LIKE '%$v%')";
}
$conditions[] = implode(' OR ', $conditions1);
}
if(!empty($this->params['url']['data']['filter']['occasion']))
{
foreach ($this->params['url']['data']['filter']['occasion'] as $v){
$conditions2[] ="`Product`.`occasion` LIKE '%$v%'";
}
$conditions[] = implode(' OR ', $conditions2);
}
}
我的以下代码正在生成此sql查询
SELECT `Product`.`id`, `Product`.`category`, `Product`.`name`, FROM mydb`.`products` AS `Product` WHERE `Product`.`category` = 'Necklace' AND (`Product`.`materialtype` LIKE '%Yellow Gold%') OR (`Product`.`materialtype` LIKE '%White Gold%') AND (`Product`.`occasion` LIKE '%Traditional%') OR (`Product`.`occasion` LIKE '%Modern%')
但我正在寻找这个输出。
SELECT `Product`.`id`, `Product`.`category`, `Product`.`name`, FROM mydb`.`products` AS `Product` WHERE `Product`.`category` = 'Necklace' AND ((`Product`.`materialtype` LIKE '%Yellow Gold%') OR (`Product`.`materialtype` LIKE '%White Gold%')) AND ((`Product`.`occasion` LIKE '%Traditional%') OR (`Product`.`occasion` LIKE '%Modern%'))
答案 0 :(得分:1)
您需要从foreach内部的语句中删除内部括号。并将其添加到外面,如下所示。
if(!empty($this->params['url']['data']['filter']['materialtype']))
{
foreach ($this->params['url']['data']['filter']['materialtype'] as $v){
$conditions1[] = "Product.materialtype LIKE '%$v%'";
}
$str_cond = implode(' OR ', $conditions1);
$conditions[] = '(' . $str_cond . ')';
}
if(!empty($this->params['url']['data']['filter']['occasion']))
{
foreach ($this->params['url']['data']['filter']['occasion'] as $v){
$conditions2[] = "Product.occasion LIKE '%$v%'";
}
$str_cond = implode(' OR ', $conditions2);
$conditions[] = '(' . $str_cond . ')';
}