1

如果该字段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.'%');
4

3 回答 3

3

我会在数据库端使用正则表达式

 $q['conditions'] = array("Groups.gp_categories REGEXP" => "[[:<:]]".$id."[[:>:]]");

(that's mysql, btw, you need to change it if you're using another db).

You could wrap that find in a model function or leave it in the controller if it's not reused somewhere else.

Example

public function getByCategory($id) {
    return $this->find('all', array('conditions'=> 
           array("Groups.gp_categories REGEXP" => "[[:<:]]".$id."[[:>:]]")));
}

//in controller
$this->YourModel->getByCategory($id);

I'm not aware if there's a more efficient function in cake, so that's a probable no. Also, you'll have to test if a regex expression in the DB is more efficient than the LIKE query you're already using, I haven't benchmarked it. But it should be more efficient than 4 likes.

于 2013-07-08T17:48:25.333 回答
0

试试这个

   $gp_categories = '12 56 34 345 349' ;
    if (strpos($gp_categories,'34') !== false) {
    echo 'true';
    }
于 2013-07-08T16:52:27.177 回答
0
Using Locate

LOCATE 的工作方式如下:

LOCATE(<string to find>, <string to find it in>)

或者

LOCATE(<string to find>, <string to find it in>, <position to start at>)

例如,要在字符串“apples oranges pears bananas apples oranges”中查找“oranges”的位置,请执行以下操作:

SELECT LOCATE("oranges", "apples oranges pears bananas apples oranges");

这将返回 8。要在源字符串中查找下一次出现的“橙子”,请将第三个参数传递给函数,告诉它在此示例中从位置 9 开始:

SELECT LOCATE("oranges", "apples oranges pears bananas apples oranges", 9);

现在将返回 37。请注意,在这些示例中,如果已将 8 作为起始位置传递,则将返回 8。

如需更多使用此功能,您可以参考链接

但是您必须将其转换为 cakephp 数组,

于 2013-07-08T17:12:37.860 回答