我正在创建一个存储在蛋糕会话变量中的候选名单
$this->Session->read('Item.shorlist');
这包含逗号分隔的 ID 列表,例如。 1,2,3,4,5
$shortlist = $this->Session->read('Item.shorlist');
我想在查找条件中使用此变量中逗号分隔的 ID 执行查找操作,例如:
$shortlist = $this->Item->find('all', array('conditions' => array('Item.id' => array($shortlist))));
但是,这仅返回 1 组数据。 如果我手动放入数组,例如:
$shortlist = $this->Item->find('all', array('conditions' => array('Item.id' => array(1,2,3,4,5))));
我已返回全部 5 条记录。
有什么想法可以解决这个问题而不需要对每个 id 执行多次查找吗?如果我查看 SQL 转储,我可以看到 WHERE
Item
.id
= ('1,2,3,4,5') 使用 $shortlist 变量,而如果我手动输入它作为逗号分隔的整数,例如: WHERE Item
.id
IN (1, 2, 3, 4) 然后sql查询按我希望的方式工作。
所以我想我的问题是如何将变量中的逗号分隔字符串转换为逗号分隔整数,以便 SQL 不会抛出错误?
当您使用此行检索会话值时,
$shortlist = $this->Session->read('Item.shorlist');
将是一个字符串,请确保它是一个数组。
使用explode
$short_list_array = explode(',', $shortlist);
函数将其转换为数组并使用
$shortlist = $this->Item->find('all', array('conditions' => array('Item.id' => $short_list_array)));
$shortlist = array_map('trim', explode(',',$shortlist));