9

I would like to pull from database multiple rows, according to a list of array of ID's.

In some other frameworks there seem to be something like "WHERE_IN", but not here.

Can someone tell me how to do it?

I would like to know how to do that through the find() or read() (or any other cakephp function) and NOT build a query manually, since I want all data to be escaped and secure.

thank you

mgPePe
  • 5,677
  • 12
  • 52
  • 85

2 Answers2

26

According to "Complex Find Functions" (third example) this should work:

$this->YourModel->find('all', array(
    'conditions' => array(
        "YourModel.id" => array(1, 2, 3, 4)
    )
));
OGHaza
  • 4,795
  • 7
  • 23
  • 29
vstm
  • 12,407
  • 1
  • 51
  • 47
  • to do the same but with id different of array? – Martin Jan 24 '13 at 18:32
  • @Martin: thank you for the question. I'm not sure what you mean - do you want to select records whose IDs are not in the array like the `NOT IN`-operator? Or do you want to select using another field than `id` – vstm Jan 25 '13 at 09:08
  • I already solved the doubt, thanks anyway http://stackoverflow.com/questions/14508682/find-where-id-is-not-in-array-of-ids/14509011#14509011 – Martin Jan 25 '13 at 09:16
  • On CakePHP 3 this throws *InvalidArgumentException: Cannot convert value to integer* – ᴍᴇʜᴏᴠ May 16 '18 at 17:27
1

It looks like in the newer CakePHPs you need to specify 'IN'. This solves aexl question.

$this->YourModel->find('all', [
    'conditions' => [
        "YourModel.id IN" => [1, 2, 3, 4]
    ]
]);
Joe C
  • 2,728
  • 4
  • 30
  • 38