我正在使用 Codeigniter 并尝试将逗号分隔列表从我的 Controller 传递到模型,以便在 where_not_in
查询中使用它。我有以下代码来创建逗号分隔列表。
$mnames = Array();
foreach($facet_group['manufacturer_name'] as $u) $mnames[] = $u['value'];
$manufacturer_list = implode(",",$mnames);
生产以下产品:阿尔卡特、苹果、华为、LG、微软、摩托罗拉、诺基亚、三星、索尼。我的查询是这样的:
$this->db->select('name');
$this->db->from('wl_manufacturers');
$this->db->where('active', 1);
$this->db->where('supplier_type', 'product');
$this->db->where_not_in('name', $str);
$str 是逗号分隔的列表
探查器的输出是:
SELECT `name`
FROM `wl_manufacturers`
WHERE `active` = 1
AND `supplier_type` = 'product'
AND `name` NOT IN('Alcatel,Apple,Huawei,LG,Microsoft,Motorola,Nokia,Samsung,Sony')
这似乎不起作用,因为列表中的每个项目都没有单引号。但是,如果我像这样手动创建列表: $array = array('Alcatel','Apple','Huawei','LG','Microsoft','Motorola','Nokia','Samsung','Sony' ).它有效,探查器的输出是:
SELECT `name`
FROM `wl_manufacturers`
WHERE `active` = 1
AND `supplier_type` = 'product'
AND `name` NOT IN('Alcatel', 'Apple', 'Huawei', 'LG', 'Microsoft', 'Motorola',
'Nokia', 'Samsung', 'Sony')
在将其传递给模型之前,我尝试在逗号分隔的列表项中添加单引号:
$str = "'" . implode ( "', '", $mnames ) . "'";
但是探查器的输出是这样的:
SELECT `name`
FROM `wl_manufacturers`
WHERE `active` = 1
AND `supplier_type` = 'product'
AND `name` NOT IN('\'Alcatel\', \'Apple\', \'Huawei\', \'LG\', \'Microsoft\',
\'Motorola\', \'Nokia\', \'Samsung\', \'Sony\'')
再次不起作用,因为添加了反斜杠。所以问题是我如何创建逗号分隔列表,将其传递到我的模型并使查询正常工作?
最佳答案
你需要分解你的逗号分隔字符串($str)来创建一个数组
$arr=explode (',',$str)
然后你可以在你的查询中使用它
$this->db->where_not_in('name', $arr);
参见 explode : 和 CI 的 where_not_in()
关于php - 将逗号分隔列表从 Controller 传递到模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47970785/