In this tutorial, We will learn how to call a model method from another model in the Codeigniter app. I will teach you how to call a model function to another model, the same model, and the controller file.
Follow some steps:
Step 1:
Create Model_1 Model File application/models/Model_1.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Model_1 extends CI_Model {
public function fun1(){
return "Model_1 fun1";
}
public function fun2(){
return "Model_1 fun2";
}
}
Step 1:
Create Model_2 Model File application/models/Model_2.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Model_2 extends CI_Model {
public function __construct() {
parent::__construct();
/* Load Models - Model_1 */
$this->load->model('Model_1');
}
public function fun1(){
/* Access Two model methods and assing response to Array */
$response[] = $this->Model_1->fun1();
$response[] = $this->Model_1->fun2();
$response[] = "Model_2 fun1";
return $response;
}
}
Step 3:
Create Route application/config/routes.php
<?php
$route['base-call'] = "BaseController";
Step 4:
Create BaseController application/controller/BaseController.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class BaseController extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('Model_2');
}
public function index(){
$response1 = $this->Model_2->fun1();
echo "<pre>";
print_r($response1);
echo "</pre>";
}
}
Output:
Array
( [0] => Model_1 fun1 [1] => Model_1 fun2 [2] => Model_2 fun1 ) |
Thanks, I hope it will work for you.........