mysql - CakePHP LIKE 语句?

标签 mysql cakephp

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

最佳答案

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

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

(这是 mysql,顺便说一句,如果您使用其他数据库,则需要更改它)。

您可以将找到的内容包装在模型函数中,或者如果不在其他地方重用,则将其保留在 Controller 中。

示例

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

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

我不知道 cake 中是否有更有效的功能,所以很可能没有。另外,您必须测试数据库中的正则表达式是否比您已经使用的 LIKE 查询更有效,我还没有对它进行基准测试。不过应该比4个赞更有效率。

关于mysql - CakePHP LIKE 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17531928/

相关文章:

php - 如何从页面上的mysql和echo链接获取数据?

mysql - 在 mysql 中连接来自 blob 的二进制数据

java - 根据主键从选择查询中分离输出结果

MySql 在存储过程中的 IF THEN END IF 中使用 OR

php - CakePHP 是否有内置函数来检查 MySQL 注入(inject)?

mysql - MySQL 中的 MAX 函数

php - CakePHP 订单查询结果超过 1 级

php - $this->Agreements->save() - 只创建一条记录,为什么?

cakephp - Cake php 模型关系的难度,尤其是。有很多通过

php - CakePHP 2.0 帐户验证