简体   繁体   English

在CodeIgniter中使用WHERE CONCAT和Active Record

[英]Using WHERE CONCAT with Active Record in CodeIgniter

The raw query I'm trying to get plugged in here is: 我试图插入的原始查询是:

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

I've checked through the AR docs and can't find anything that would allow me to do this. 我已经通过AR文档检查过,找不到任何可以让我这样做的东西。 I'm not very familiar with how exactly it's constructing these queries, and was hoping someone could point me in the right direction. 我不太熟悉它是如何构建这些查询的,并且希望有人可以指出我正确的方向。 Thanks a bunch. 谢谢一堆。

If you want to use the AR class you need to pass FALSE as third parameter to avoid the query being escaped automatically. 如果要使用AR类,则需要将FALSE作为第三个参数传递,以避免查询自动转义。 You are now left to escaping the argument by yourself: 你现在可以自己逃避争论了:

$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();

Refer to point 4) in the Active Record session of the manual. 请参阅本手册的Active Record会话中的第4点)。 Quoting: 引用:

   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);

An easier way, imho, whould be to run a "regular" query and take advantage of binding: 一种更简单的方法,即imho,可以运行“常规”查询并利用绑定:

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

something like this should work: 这样的事情应该有效:

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

$this->db->get(x);

Or use an associative array method without using the third parameter: 或者在不使用第三个参数的情况下使用关联数组方法:

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

Will be generated WHERE part of the query: 将生成WHERE部分查询:
... WHERE CONCAT(`y`, " ", `x`) LIKE '%test value%' AND `title` LIKE '%test title%' AND ...
Obviously useful when using more than one search parameters. 使用多个搜索参数时显然很有用。

This is old but... 这已经过时了......

You can try this: 你可以试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM