如何使用活动记录在类似的SQL查询中转义参数?

时间:2016-03-19 21:23:35

标签: sql activerecord codeigniter-3

用parentesis查询:

SELECT * 
FROM users 
WHERE company_id = 1 AND (
    name LIKE "%smith%" OR 
    last_name LIKE "%smith%"
)

但是在codeigniter中有:

$query_members = $this->db
    ->select('users.*')
    ->from('users')
    ->like(array('users.names' => $search))
    ->or_like(array('users.last_name' => $search))
    ->where(array('users.company_id' => 1));

生成:

SELECT * 
FROM users 
WHERE 
    name LIKE '%smith%' OR 
    last_name LIKE '%smith%' AND 
    company_id = 1;

并且不起作用,我需要((a或b)和c),而不是(a或b和c)。我在这里找到了解决方案:Codeigniter parentheses in dynamic Active Record query但变量使用完整引号进行转义,我需要使用"%"前值和后值。我有这个:

$search_escaped = $this->db->escape($search);
$query_members = $this->db
    ->select('users.*')
    ->from('users')
    ->where('(users.names LIKE "%'.$search_escaped.'%" OR users.last_name LIKE "%'.$search_escaped.'%")')
    ->where(array('members.company_id' => (int)$company_id));

但查询添加了错误的引号:

SELECT `users`.*
FROM `users`
WHERE (users.names LIKE "%'smith'%" OR users.last_name LIKE "%'smith'%")
AND `members`.`company_id` = 2

"%&#;;史密斯'%"引用不好。我如何通过使用codeigniter 3.0.0的活动记录来解决这个问题?

0 个答案:

没有答案