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

Asked

Viewed 31 times

1

I have an SQL that returns to me the following:

1: Hacker And Automobiles

OR

2: Food

and I need her to return to me:

1: Hacker

And

2: Cars 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);  
            }    
        }
    }

One parentheses missing in condition where/or_where of bc_urllink I don’t know how to put.

In pure SQL, it’s 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 your help.

1 answer

1


You have to use the query-grouping, commands:

$this->db->group_start();

and here you put the conditions and finish:

$this->db->group_end();


applying in your code, within the if, some modifications have been made:

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

  • 1

    What a TOP this group hein @Virgilio, thanks guy.

  • Cool even @Marcosvinicius !!! ball show we have all the options ... vlw

Browser other questions tagged

You are not signed in. Login or sign up in order to post.