Search code examples
phpsqlcodeigniterwhere-clausequery-builder

Conditionally add an OR WHERE IN () condition using CodeIgniter's query building methods


I am trying to combine these two queries in CodeIgniter. The row either has to have the user_id of $user (eg 3 OR) have an id in the $repost array. I know how to use or_where() but how do you do or_where_in()?

$this->db->where("user_id", "$user");
if (isset($conditions["repost"])) {
    $user_favourited = $conditions["repost"];
        
    $this->db->where("user_id", $user_favourited);
    $this->db->select("post_id");
    $this->db->from($this->repost_table);
    $query = $this->db->get();
    
    $id['posts'] = $query->result_array();
    
    foreach ($id['posts'] as $post) {
        $repost[] = $post['post_id'];
    }
    
    if (isset($repost)) {
        $this->db->where_in('id', $repost);
    }
}

Solution

  • $this->db->or_where_in();
    

    Syntax:

    or_where_in([$key = NULL[, $values = NULL[, $escape = NULL]]])
    

    Parameters:

    $key (string) – The field to search
    $values (array) – The values searched on
    $escape (bool) – Whether to escape values and identifiers
    

    Returns:

    DB_query_builder instance
    

    Return type:

    object
    

    Generates a WHERE field IN(‘item’, ‘item’) SQL query, joined with ‘OR’ if appropriate.

    More information here: https://codeigniter.com/userguide3/database/query_builder.html?highlight=or_where_in#CI_DB_query_builder::or_where_in