如果字段gp_categories包含字符串'12 56 34 345 349',如何查找包含数字34的记录?
$id = 34;
// 1. Works but is there a more efficient way?
$q['conditions']['OR'] = array(
array('Groups.gp_categories LIKE' => $id), // Only
array('Groups.gp_categories LIKE' => $id.' %'), // Start
array('Groups.gp_categories LIKE' => '% '.$id.' %'), // Middle
array('Groups.gp_categories LIKE' => '% '.$id) // End
);
// 2. Finds either 34, 345, 349 etc
$q['conditions'] = array('Groups.gp_categories LIKE' => '%'.$id.'%');发布于 2013-07-09 01:48:25
我会在数据库端使用正则表达式
$q['conditions'] = array("Groups.gp_categories REGEXP" => "[[:<:]]".$id."[[:>:]]");(这是mysql,顺便说一句,如果你正在使用另一个数据库,你需要改变它)。
您可以将该查找包装在模型函数中,或者如果它没有在其他地方重用,则将其留在控制器中。
示例
public function getByCategory($id) {
return $this->find('all', array('conditions'=>
array("Groups.gp_categories REGEXP" => "[[:<:]]".$id."[[:>:]]")));
}
//in controller
$this->YourModel->getByCategory($id);我不知道蛋糕中是否有更有效的函数,所以这可能是不可能的。此外,您还必须测试DB中的正则表达式是否比您已经使用的LIKE查询更有效,我还没有对其进行基准测试。但它应该比4个赞更有效。
发布于 2013-07-09 00:52:27
尝尝这个
$gp_categories = '12 56 34 345 349' ;
if (strpos($gp_categories,'34') !== false) {
echo 'true';
}发布于 2013-07-09 01:12:38
Using LocateLOCATE的工作方式如下:
LOCATE(<string to find>, <string to find it in>)或
LOCATE(<string to find>, <string to find it in>, <position to start at>)例如,要在字符串“apple oranges pears bananas apple oranges”中查找"oranges“的位置,请执行以下操作:
SELECT LOCATE("oranges", "apples oranges pears bananas apples oranges");这将返回8。要查找源字符串中下一个出现的"oranges“,请将第三个参数传递给函数,告诉它从本例中的位置9开始:
SELECT LOCATE("oranges", "apples oranges pears bananas apples oranges", 9);现在将返回37。请注意,在这些示例中,如果将8作为起始位置传递,则将返回8。
要想获得更多的用法,你可以通过refer link
但是您必须将其转换为cakephp数组,
https://stackoverflow.com/questions/17531928
复制相似问题