Search code examples
phpapicodeignitercontrollercodeigniter-4

how to access two different model in single controller in Codeigniter 4?


I am a new and beginner in Codeigniter 4, so I am asking that question.

Actually, I have two different models.

First is tbl_user.

In there are many fields tbl_user(id, name,duty_station,enlistment_date,dob) // here id is the primary key.

Second is usermos.

usermos has four fields [id, user_id, mos_id, additional_mos_id] //hereid is primary keyand user_id is forign key to tbl_user

I have generated the controller of get_profile...

I would like to access usermos model into get_profile controller.

Following is my code

Headers

<?php namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use App\Models\MosModel;
use App\Models\Additional_mosModel;
use App\Models\Api_auth_model;
use App\Models\Api_Usermos_Model;

Controller

public function get_profile()
    {
     
      if (($this->request->getMethod() == 'post') && ($_SERVER['PHP_AUTH_USER'] == AUTHUSER_NAME) && ($_SERVER['PHP_AUTH_PW'] == AUTH_PASSWORD)) {
        if(!empty($this->request->getPost('id'))){

          $user_api_mos_model = new Api_Usermos_Model();
        $usermos = $this->user_api_mos_model->findAll();
           print_r($usermos);
           exit;
        if($profile){
          if($usermos){
          
          }
          $selected_mos = $this->getMosFromID($usermos[0]['mos_id']);
         
          $selected_add_mos = $this->getAdd_MosFromID($usermos[0]['additional_mos_id']);
          $profile['badge'] = $this->getBadgeFromID($profile['badge_id']);
          // exit;
          return $this->respond([
            "status" => "Success",
            "message" => "Profile found.",
            "Common" => ["Title" => "Load Profile API", 'version' => '1.0', 'Description' => 'Load Profile API', 'Method' => 'POST'],
            "Response" => ["Userdata" => $profile,"mos" => $selected_mos,"additonal_mos" => $selected_add_mos]
          ]);
        }else{
          return $this->respond([
            "status" => "Fail",
            "message" => "Profile Not found.",
            "Common" => ["Title" => "Load Profile API", 'version' => '1.0', 'Description' => 'Load Profile API', 'Method' => 'POST'],
            "Response" => ["Value" => 'Profile Not found.']
          ]);
        }
      }
    }
  }

Thanks for your valuble time.


Solution

  • Simply define the namespace of the model in top of the controller page header section and use in that controller page. For example:

    <?php namespace App\Controllers;
     
    use  app\models\User;
    use app\models\Usermos;
    
    Class UserController extend controller {
        public function actionProfile (){
    
          $user = new User();
          $user_mos = new Usermos();
       }
    }