[英]How can I search for comma separated values in database using codeigniter
I am trying to filter a database by having a category column, so I search for the category and the correct items are returned.我正在尝试通过具有类别列来过滤数据库,因此我搜索类别并返回正确的项目。 However some items have more than one category so I have used comma separated values to put two or more categories in one column.
然而,有些项目有不止一个类别,所以我使用逗号分隔值将两个或多个类别放在一列中。 I tried this method:
我试过这个方法:
public function get_cat_article($value)
{
$table = $this->get_table();
$this->db->where('cat', $value);
return $this->db->get($table);
}
but that only picks up the first of the separated values.但这只会获取第一个分离值。 I tried using 'where_in' but that also picked up only the first value.
我尝试使用 'where_in' 但也只获得了第一个值。 I tried 'like' and that worked but was not definitive.
我试过“喜欢”,效果很好,但不是确定的。 A search for 'WS' included other categories like 'IWS'.
搜索“WS”包括其他类别,如“IWS”。 I googled for a solution and fin_in_set was suggested so I tried:
我在谷歌上搜索了一个解决方案,并建议使用 fin_in_set,所以我尝试了:
public function get_cat_article($value)
{
$table = $this->get_table();
$this->db->where('find_in_set('.$value.',cat)');
return $this->db->get($table);
}
But this didn't work at all.但这根本不起作用。 Have I got the syntax wrong or is this the wrong approach?
我的语法错误还是这是错误的方法?
Have you tried like query?你试过像查询吗? In a quick demo, this works for me.
在一个快速演示中,这对我有用。
public function get_cat_article($value)
{
$table = $this->get_table();
$this->db->like('cat', $value); // say, $value = 'reebok'
return $this->db->get($table);
// Produces: SELECT * FROM $table WHERE `cat` LIKE '%reebok%' ESCAPE '!'
}
For more details read CodeIgniter official user guide here .有关详细信息,请 在此处阅读 CodeIgniter 官方用户指南。
Try like method but this way:尝试类似的方法,但是这样:
public function get_cat_article($value)
{
$table = $this->get_table();
$this->db->like('cat', $value . ',', 'after');
$this->db->or_like('cat', ',' . $value . ',');
$this->db->or_like('cat', ',' . $value, 'before');
return $this->db->get($table);
}
The problem appears to be solved using the following line of code using the MySql 'find_in_set' technique.该问题似乎可以通过使用 MySql 'find_in_set' 技术的以下代码行来解决。 I got the code from this website at Check the conditions in comma separated values and the key line is:
我在检查逗号分隔值中的条件时从该网站获得了代码,关键行是:
$this->db->where("FIND_IN_SET( '$post_period' , period) ");
I just got the syntax wrong.我只是语法错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.