In codeigniter, how do I make a connection with a where clause

therefore, I have two tables, and I want to get all the rows from table 1 that satisfy the conditions of the where clause, and then join them to table 2 based on the join conditions.

Here are sample tables:

table1:

col1   col2  col3
1      a     val1
2      b     val2
3      c     val3

table2:

col1   col3
1      someval1
2      someval2
3      someval3

now I want to grab all the rows in table 1, where col1 = 2, and connect these rows to the rows from table2, where table2.col1 = table1.col1. It makes sense?

+5
source share
3 answers

It has been a while since I wrote CI, but on this documentation page your solution might look like this:

$this->db->select('*');
$this->db->from('table1');
$this->db->join('table2', 'table1.col1 = table2.col1');
$this->db->where('table1.col1', 2);

$query = $this->db->get();

Note that this answer can in no way be construed as endorsement of working with Code Igniter; -)

+14

:

$this->db->select('*'); // Select field
$this->db->from('table1'); // from Table1
$this->db->join('table2','table1.col1 = table2.col1','INNER'); // Join table1 with table2 based on the foreign key
$this->db->where('table1.col1',2); // Set Filter
$res = $this->db->get();

, :)

+2
$this->db->select('book_id, book_name, author_name, category_name');
$this->db->from('books');
$this->db->join('category', 'category.category_id = books.category_id');
$this->db->where('category_name', 'Self Development');
$query = $this->db->get();

// Produces SQL:
 select book_id, book_name, author_name, category_name from books 
 join category on category.category_id = books.category_id 
 where category_name = "Self Development"
0

All Articles