- In CodeIgniter, the Model is used for the Database manipulation – fetch, insert, update, and delete records.
- If within the project there are multiple Models are available then it may require to perform the action during a Model which is already created in another Model.
- In this case, you’ll either create a separate function to perform an equivalent action or use the already available method within the Model.
- It is possible to reuse the method in the Model from another Model.
- Models are loaded within the Model as same as loaded within the Controller using $this->load->model().
- Create Three Models and call 1st and 2nd Model methods from the 3rd Model.
1.Configuration
Default controller
Open application/config/routes.php and edit default_controller value to User.
$route[‘default_controller’] = ‘User’;
2.Model 1 : Call Model method from another Model
Create a new Model_1.php file in application/models/ directory.
Create two methods –
- fun1()
- fun2()
which returns string text.
Code
3.Model 2 : Call Model method from another Model
Create a new Model_2.php file in application/models/ directory.
Create two methods –
- fun1()
- fun2()
which returns string text.
Code
4.Model 3 : Call Model method from another Model
Create a new Model_3.php file in application/models/ directory.
In this Model, I loaded 2 Models – Model_1 and Model_2 and access their methods.
- Syntax – Load and Access Model
$this->load->model(‘Model_name’); // Load Model
$this->Model_name->method_name(); // Access Method
- Load Models –
__construct – Load Model_1 and Model_2 using $this->load->model().
- Access Two methods –
fun1 – Call fun1() method of Model_1 $this->Model_1->fun1() and assign response in $response Array. Similarly call fun1() method of Model_2 $this->Model_2->fun1() and assign to $response Array.
Return $response.
- Access Single method –
fun2 – Call fun2() method of Model_2 $this->Model_2->fun2() and assign response in $response Array
Return $response.
Code
5.Controller
- Create a new User.php file in application/controllers/ directory.
- Load Model_3 Model and call fun1() and fun2() methods.
- Print the response.
Code
6.Output
It gives the following output –
Conclusion
Use $this->load->model() method to load the Model and access methods same as accessed from the Controller.