Thursday, January 13, 2022

[FIXED] CakePHP paginate condition

Issue

I’d like to search multiple items copied from excel. These skus are separated by empty space. Search result is always empty because each condition should be OR not AND. How can I change paginate condition from AND to OR?

Query Result

SELECT *, ParentProduct.id FROM parent_products AS ParentProduct WHERE 
ParentProduct.name LIKE '%na301mo%' AND ParentProduct.name LIKE '%gf001bh%' AND 
ParentProduct.name LIKE '%cc302bf%' LIMIT 10

Search values

na301mo gf001bh cc302bf

Controller

    if (empty($results)) {
        $this->paginate['conditions'] = $this->ParentProduct->resetConditions($searchStr, 'multi-skus');
        $results = $this->paginate('ParentProduct');
    }

Model

    public function resetConditions($searchStr, $opt) {
        if ($opt == ‘multi-skus’) {
            $conditions = array();
            $searchStr = preg_replace('!\s+!', ' ', $searchStr);
            $search_terms = explode(' ', $searchStr);
            foreach ($search_terms as $search_term) {
                $conditions[] = array($this->name . '.sku LIKE' => '%' . $search_term . '%');
            }
        } 
    }

Version. 1.3x

Please advise. Thank you


Solution

You will need to change foreach loop inside your resetConditions Medhod Like below:

            foreach ($search_terms as $search_term) {
                $conditions['OR'][] = array($this->name . '.sku LIKE' => '%' . $search_term . '%');
            }

This will make sure that all Search Terms are separated by OR instead of AND



Answered By - ascsoftw

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.