使用关联数组的多个 LIKE 数据库查询 - 但全部来自相同的列名...?
我正在尝试使用 CodeIgniter 的活动记录类查询我的数据库。我在一个表中存储了许多博客文章。该查询用于搜索功能,它将拉出所有分配有特定类别的帖子。因此,表的“类别”列将列出该帖子的所有类别,无特定顺序,用逗号分隔,如下所示:政治、历史、社会学。等等。
如果用户选择政治和历史,则应返回同时具有这两个类别的所有帖子的标题。
因此,查询的类别列表将是数组 $cats。我认为这会起作用-
foreach ($cats as $cat){
$this->db->like('categories',$cat);
}
通过产生这个:(
$this->db->like ('categories','Politics');
$this->db->like ('categories','History');
这会产生-'WHERE类别如'%政治%'和类别如'%历史%')
但它不起作用,它似乎只产生第一个语句。我猜想的问题是每个链接查询的列名都是相同的。 CI 用户指南中似乎没有任何关于此的内容(http://codeigniter. com/user_guide/database/active_record.html),因为他们似乎假设每个链接语句都将用于不同的列名称。
当然,不可能在一个语句中使用关联数组,因为它必须包含重复的键 - 在这种情况下,每个键都必须是“类别”...
I'm trying to query my database using CodeIgniter's active record class. I have a number of blog posts stored in a table. The query is for a search function, which will pull out all the posts that have certain categories assigned to them. So the 'category' column of the table will have a list of all the categories for that post in no particular order, separated by commas, like so: Politics, History, Sociology. etc.
If a user selects, say, Politics, and History, The titles of all the posts that have BOTH these categories should be returned.
So, the list of categories queried will be the array $cats. I thought this would work-
foreach ($cats as $cat){
$this->db->like('categories',$cat);
}
By Producing this:
$this->db->like ('categories','Politics');
$this->db->like ('categories','History');
(Which would produce- 'WHERE categories LIKE '%Politics%' AND categories LIKE '%History%')
But it doesn't work, it seems to only produce the first statement. The problem I guess is that the column name is the same for each of the chained queries. There doesn't seem to be anything in the CI user guide about this (http://codeigniter.com/user_guide/database/active_record.html) as they seem to assume that each chained statement is going to be for a different column name.
Of course it is not possible to use an associative array in one statement as it would have to contain duplicate keys- in this case every key would have to be 'categories'...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于 MySQL,我刚刚在数据库上运行了以下查询,没有出现任何问题。
同样,以下代码按预期运行:
如果您在 CI 中使用“like”函数,则必须使用正确的查询函数为它们添加前缀和后缀,例如:
With regard to MySQL, I just ran the following query on my database and there were no issues.
Likewise the following code ran as expected:
If you're using the 'like' function in CI, you have to prefix and postfix them with the proper query functions, example:
你可以使用下面的代码
you can use following code