Codeigniter 4 – Method Chaining with Example
Method Chaining
- Method chaining is a technique used to call multiple methods on an object in a single statement.
- In CodeIgniter 4, method chaining is used extensively in the Query Builder and other classes.
Query Builder Method Chaining
- Use method chaining to build complex queries.
Example:
$db->select('name, email')->from('my_table')->where('name', 'John Doe')->where_in('id', [1, 2, 3])->get();
Chaining Select and From
- Use method chaining to specify the columns and table.
Example:
$db->select('name, email')->from('my_table')->get();
Chaining Where and Where In
- Use method chaining to filter data based on conditions.
Example:
$db->select('name, email')->from('my_table')->where('name', 'John Doe')->where_in('id', [1, 2, 3])->get();
Chaining Join and Group By
- Use method chaining to join tables and group data.
Example:
$db->select('my_table.name, another_table.email')->from('my_table')->join('another_table', '(link unavailable) = (link unavailable)')->group_by('my_table.name')->get();
Chaining Order By and Limit
- Use method chaining to sort and limit data.
Example:
$db->select('name, email')->from('my_table')->order_by('name', 'ASC')->limit(10)->get();
Chaining Insert and Update
- Use method chaining to insert and update data.
Example:
$db->insert('my_table', ['name' => 'John Doe', 'email' => 'john@example.com'])->update('my_table', ['name' => 'Jane Doe'], ['id' => 1]);
I hope this helps! Let me know if you have any further questions or need more information.
Note: Method chaining is a powerful technique used in CodeIgniter 4 to build complex queries and perform database operations in a readable and maintainable way.