Search in two tables with codeigniter

Asked

Viewed 510 times

1

I have the following situation:

inserir a descrição da imagem aqui

When selecting a marca in tabela compatibility, I want to list all products in the Product table, whose code is equal to the code of the selected brand.

Example: when selecting Toyota should list Cabin, Lighthouse and Wheel and when selecting Mazda should return only Cabin

I did the following:

$marca = $this->input->post('marca');
$marca = explode(',', $marca);    
$query = array();
if (count($marcas) > 0) 
{
    $i = 0;         
    foreach ($comp as $row) 
    {
        $i++;
        if ($row !== "") 
        {
            if ($row !== "0") 
            {
                $query[] = $row;
                $this->db->where_in('marca', $query);
            }
        } 
    }
}

But with this code I can only get the products with the following table:

inserir a descrição da imagem aqui

What can I program to make the relation of the two tables through the field codigo?

  • and then the solution helped you?

  • Good, The solution was very useful, but I could not do what I expected in my script, so I changed the composition of the tables to make my search even easier... instead of using two tables I will use a table... and use the json_decode function

1 answer

1

To solve your problem is simple, the code below exemplifies what you need to encode:

$this->db
     ->from('compatibilidade')
     ->join('produto', 'compatibilidade.codigo=produto.codigo')
     ->where('compatibilidade.marca', $marca)
     ->select('produto.*, compatibilidade.marca')
     ->get()
     ->result_array();

Some observations may improve the performance of that SQL

  • Create an entry in the fields codigo of the two tables, example:

inserir a descrição da imagem aqui

  • Create an entry in the field marca

inserir a descrição da imagem aqui

As I do not know your business rule well, as your programming could even create a relationship in the two fields, but, what was exemplified enough to solve your problem.

Reference: Query Builder Class

Browser other questions tagged

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