Sho
Sho

Reputation: 353

How to find fields by an array which contains multiple values by using like %% search

I am trying to get multiple fields which match to those ids(1, 2, 3) by Like %% search. I have tried to make it work for two hours, but it hasn't worked though it looks pretty simple.

$ids = array ('1','2','3');

$result = $this -> Model -> find ('all', array(
    'conditions' => array( 'Model.category LIKE' => '%'.$ids.'%')
));

I need somebody's help.

Upvotes: 2

Views: 113

Answers (5)

Sho
Sho

Reputation: 353

Sorry for the late reply, and thank you for answering my question. As long as I read your answers, the ansewer Nick Zinger posted was the most helpful. However, what I'd like to do was AND search. So I improved the answer like bellow.

$ids = array ('1','2','3');
$conditions = array();
foreach($ids as $id){
    $conditions['AND'][] = array( 'Model.category LIKE' => '%'.$id.'%')
}

$result = $this->Model->find('all', array('conditions'=>$conditions));

Again, I really appreciate for your helps.

Upvotes: 1

Jelle Keizer
Jelle Keizer

Reputation: 721

Havent tested it but this should work

$ids = array(1, 2, 3);

$result = $this->Model->find('all', array(
    'conditions' => array('Model.category'=>$ids ')
        ));

Upvotes: 0

Nick Zinger
Nick Zinger

Reputation: 1174

I'd suggest you build the 'conditions' array separately. For example:

$ids = array ('1','2','3');
$conditions = array();
foreach($ids as $id){
    $conditions['OR'][] = array( 'Model.category LIKE' => '%'.$id.'%')
}

$result = $this->Model->find('all', array('conditions'=>$conditions));

Upvotes: 1

p0d4r14n
p0d4r14n

Reputation: 681

Just a guess but try it like

'Model.category LIKE' => "%$ids%"

Upvotes: 0

Vineet
Vineet

Reputation: 4645

See CakePHP how to get multiple rows by array of ID's

$this->YourModel->find('all', array(
    'conditions' => array(
        "YourModel.id" => array(1, 2, 3, 4)
    )
));

Upvotes: 0

Related Questions