如果字段 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/