How to use query builder join in Codeigniter 4

In CodeIgniter 4, the Query Builder provides a simple and convenient way to perform database queries, including joins. To use joins with the Query Builder, you will need to load the database library and then use the join() method to specify the join conditions. Here's a step-by-step guide on how to use the Query Builder join in CodeIgniter 4:

Step 1: Load the Database Library

Before using the Query Builder, you need to load the database library. You can do this in your controller or model where you want to perform the database operations. Open your controller or model file and load the database library as follows:

// If you are in a controller:
$builder = $this->db;

// If you are in a model:
$builder = $this->db->table('your_table_name');

Step 2: Perform the Join

Use the join() method of the Query Builder to perform the join. The join() method takes two main arguments: the table name you want to join and the join condition. You can also specify the type of join (e.g., inner join, left join, right join) as the third argument. If you omit the third argument, an inner join is used by default.

Here's the basic syntax for joining two tables:

$builder->join('table_name', 'join_condition', 'join_type');


Let's say you have two tables: orders and customers, and you want to retrieve all orders along with their corresponding customer information using the customer_id field as the join condition.

// Assuming you are in a controller or model and have already loaded the database library
$builder = $this->db->table('orders');

$builder->join('customers', ' = orders.customer_id', 'left');

In this example, we are performing a left join between the orders and customers tables using the customer_id field as the join condition.

Step 3: Perform Other Operations and Execute the Query

After specifying the join, you can continue building your query using other methods provided by the Query Builder, such as select(), where(), groupby(), orderby(), etc.

Finally, to execute the query and get the result, you can use the get() method or any other relevant method depending on your desired output format.

$results = $builder->get()->getResult();

That's it! You've successfully used the Query Builder to perform a join in CodeIgniter 4. Remember to consult the CodeIgniter 4 documentation for more information on the Query Builder and its available methods.

Muhammad Alfaiz
Alfaiz 7 months ago
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x