将数组传递给codeigniter中的活动记录

Moh*_*ian 0 php arrays activerecord codeigniter

我想like在codeignter中将数组传递给活动记录的子句,因为我写了以下内容:

like

like

在模型中:

like

但我得到了

like like

任何帮助或建议将是一个很大的帮助..提前感谢

在这里看到更新的问题: 在使用or_like codeigniter时加入不提供所需的结果

Rya*_*yan 6

你不能只是将数组传递给like()函数,它必须是一个字符串.您需要为like字符串中的每个关键字应用一个子句.

但是,您需要使用or_like将记录与任一关键字匹配,因为如果您like()每次只使用它,则需要匹配所有关键字,因为查询类似LIKE "%smart" AND LIKE "%intelligent"等等,这不是您所需要的.

$array_string = "smart,intelligent,awesome";
$array_like = explode(',', $array_string);
foreach($array_like as $key => $value) {
    if($key == 0) {
        $this->db->like('topic', $value);
    } else {
        $this->db->or_like('topic', $value);
    }
}
Run Code Online (Sandbox Code Playgroud)

尝试这种方法可以避免where忽略语句其余部分的问题.

$array_string = "smart,intelligent,awesome";
$array_like = explode(',', $array_string);

$like_statements = array();

foreach($array_like as $value) {
    $like_statements[] = "topic LIKE '%" . $value . "%'";
}

$like_string = "(" . implode(' OR ', $like_statements) . ")";
Run Code Online (Sandbox Code Playgroud)

价值$like_string将是(topic LIKE '%smart%' OR topic LIKE '%intelligent%' OR topic LIKE '%awesome%')

然后$like_string,您可以使用以下方式使用ActiveRecord:

$this->db->where($like_string, FALSE);
Run Code Online (Sandbox Code Playgroud)