cakephp与条件分页

时间:2015-07-22 12:25:12

标签: php cakephp pagination string-concatenation

我已经定义了条件变量值。我需要写这个合成器,我该怎么写呢。

$this->Paginator->settings = array('conditions' => array(
    if(!empty($this->request->data['filter']['delivery']))
    {
    'Gig.delivery <=' => $this->request->data['filter']['delivery'],
    }
    if(!empty($this->request->data['filter']['delivering']))
    {
    "Gig.bangsalsodelivering IN ({$csv_deliveringfilters})",
    }
    if(!empty($this->request->data['filter']['servicetype']))
    {
    "Gig.bangsservicetype IN ({$csv_bangsservicetypesfilters})",
    }
    if(!empty($this->request->data['filter']['style']))
    {
    "Gig.bangsstyles IN ({$csv_stylefilters})",
    }
    if(!empty($this->request->data['filter']['fileformate']))
    {
    "Gig.bangsfileformates IN ({$csv_fileformatefilters})",
    }
));
$agetGigsItem = $this->Paginator->paginate('Gig');

1 个答案:

答案 0 :(得分:2)

条件通常是数组

条件通常作为数组处理,不作为作为字符串处理。例如:

$this->Paginator->settings = [
    'conditions' => ['Gig.field' => 'is this value']
];

$agetGigsItem = $this->Paginator->paginate('Gig');

将应用此sql条件:

WHERE Gig.field = "is this value"

使用字符串连接构建条件一个坏主意。除了更麻烦之外,这意味着您需要自己处理用户输入的转义。

工作解决方案

考虑到问题中的代码,这可以做出要求:

$conditions = [];
$filter = $this->request->data['filter'];

if(!empty($filter['delivery'])) {
    $conditions['Gig.delivery <='] = $filter['delivery'];
}

if(!empty($filter['delivering'])) {
    $conditions['Gig.bangsalsodelivering'] = explode(',', $filter['delivering']);
}

if(!empty($filter['servicetype'])) {
    $conditions['Gig.bangsservicetype'] = explode(',', $filter['servicetype']);
}

if(!empty($filter['style'])) {
    $conditions['Gig.bangsstyles'] = explode(',', $filter['style']);
}

if(!empty($filter['fileformate'])) {
    $conditions['Gig.bangsfileformates'] = explode(',', $filter['fileformate']);
}

$this->Paginator->settings['conditions'] = $conditions;
$agetGigsItem = $this->Paginator->paginate('Gig');

请注意,数组值会自动转换为IN ()条件子句,如果不等于,则进行比较 - 在​​数组键中。

请务必检查the documentation您所使用的版本,了解有关how to use paginationhow to query the database的详情。