将WHERE CONCAT与CodeIgniter中的活动记录一起使用


Using WHERE CONCAT with Active Record in CodeIgniter

我试图插入的原始查询是:

SELECT * FROM x WHERE CONCAT(y, ' ', x) LIKE '%value%';

我已经查看了AR文档,找不到任何可以让我这样做的东西。我不太熟悉它是如何构建这些查询的,我希望有人能给我指明正确的方向。非常感谢。

如果您想使用AR类,您需要传递FALSE作为第三个参数,以避免自动转义查询。你现在只能自己逃避争论了:

$value = $this->db->escape_like_str($unescaped);
$this->db->from('x');
$this->db->where("CONCAT(y, ' ', x) LIKE '%".$value."%'", NULL, FALSE);
$result = $this->db->get();

请参阅本手册活动记录会话中的第4)点。报价:

   Custom string:
   You can write your own clauses manually:
   $where = "name='Joe' AND status='boss' OR status='active'";
   $this->db->where($where);
   $this->db->where() accepts an optional third parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks.
   $this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);

imho,一种更简单的方法是运行"常规"查询并利用绑定:

$result = $this->db->query("CONCAT(y, ' ', x) LIKE '%?%'", array($value));

或者使用关联数组方法而不使用第三个参数:

$a = array(
    'CONCAT(`y`, " ", `x`)' => $value,
    'title' => $title,
    ...
);
...
$this->db->like($a);

将在查询的WHERE部分生成:
... WHERE CONCAT(`y`, " ", `x`) LIKE '%test value%' AND `title` LIKE '%test title%' AND ...
当使用多个搜索参数时,显然很有用。

这样的东西应该可以工作:

$this->db->where("CONCAT(y, ' ', x) LIKE '%value%'");
$this->db->get(x);

这是旧的,但。。。

你可以试试这个:

$this->db->like('CONCAT(field_name," ",field_name_b)',$this->db->escape_like_str('value'));