How to modify this query to get the desired result in Codeigniter?

1

I have a SQL that returns me the following:

  

1: Hacker And Cars

     

OU

     

2: Food

I need to get it back:

  

1: Hacker

     

E

     

2: Automotive OR Food

The code I have so far is:

    if(!$final['termo'] == null) {

        $this->db->like('bl_title', $final['termo']);
    }

    if(!$final['categorias'] == null) {

        $c = 0;

        foreach($final['categorias'] as $cats){

            $c++;

            if($c == 1){

                $this->db->where('bc_urllink', $cats);

            } else {

                $this->db->or_where('bc_urllink', $cats);  
            }    
        }
    }

There is a missing parenthesis in the where/or_where condition of bc_urllink that I do not know how to put.

In pure SQL, it looks like this:

    $result = $this->db->query("
                                SELECT * FROM blogs AS bl 
                                INNER JOIN blog_categoria AS blc 
                                ON bl.bc_id = blc.id 
                                WHERE bl.bl_title 
                                LIKE '%Hackers%'
                                AND (blc.bc_urllink = 'automoveis'
                                OR blc.bc_urllink = 'alimentacao')
                                ");

Thanks for the help.

    
asked by anonymous 19.11.2016 / 15:58

1 answer

1

You have to use query-grouping commands: / p>

  

$this->db->group_start();

and here you put the conditions and ends:

  

$this->db->group_end();

Applying in your code, within if , you have made some modifications:

if(!$final['termo'] == null) 
{
    $this->db->like('bl_title', $final['termo']);
}

if(!$final['categorias'] == null && count($final['categorias']) > 0) 
{

    $c = 0;        
    $this->db->group_start(); //inicia o grupo
    foreach($final['categorias'] as $cats)
    {
        $c++;
        if($c == 1)
        {
            $this->db->where('bc_urllink', $cats);

        } 
        else 
        {
            $this->db->or_where('bc_urllink', $cats);  
        }    
    }
    $this->db->group_end(); // termina o grupo
}

Reference:

CodeIgniter - query-grouping

    
19.11.2016 / 16:10