CakePHP,通过一个或多个 ID 选择 MySQL 记录


CakePHP, selecting MySQL records by one or more Ids

我想根据从以下位置调用的 Id 列表选择 MySQL 记录:

$ids = $this->params['url']['ids']

其中 id 是一个或多个 Id,用逗号分隔。 我知道我可以使用爆炸来获取数组中的 Id:

$id = explode(",", $ids);

我知道通过 Id 调用的基本代码是:

$row = $this->Model->find('all',
       array(
              'conditions' => array(
                   'id' => $id['0'],
              ),
              'fields' => array(
                   'id',
                   'name'
              )
       ));

我的问题是,如何在不知道我事先拥有的ID数量的情况下使用多个ID进行选择? 即 1 个 ID,或 3 个 ID,或 5 个等。

似乎这应该适用于'id' => $id. 也就是说,传入要搜索的 ID 数组以使用 IN 子句。

将$id作为数组传递,CakePHP自动检测数组是否在条件中给出,它会自动将"="更改为"IN"mysql。

$row = $this->Model->find('all',
       array(
              'conditions' => array(
                   'id' => $id,
              ),
              'fields' => array(
                   'id',
                   'name'
              )
       ));