I am unable to change the model value, whenever I try echo the model name (After changing using if condition) the correct modelname value is displayed but if I try to call it using declared modelname value (ignores the changed value) it uses the declared model name from 'line 8 ' i.e. protected $modelName = '';
<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\HTTP\IncomingRequest;
use DateTime;
class igmc_pat_dat extends ResourceController
{
protected $modelName = '';
protected $format ='json';
protected $requestedModule;
public function index(){
$request = service('request');
$fromDate = $request->header('fromDate')->getValue();
$toDate = $request->header('toDate')->getValue();
$requestedModule = $request->header('module-code')->getValue();
$temtodate = DateTime::createFromFormat('d/m/Y h:i:s', $toDate);
$formatedtoDate=$temtodate->format("Y-m-d h:i:s");
$ddd= DateTime::createFromFormat('d/m/Y h:i:s', $fromDate);
$formatedDate = $ddd->format("Y-m-d h:i:s");
// $pat_rec = $this->model->where('datetime_of_txn >', $formatedDate)->where('datetime_of_txn <', $formatedtoDate)->findAll();
// return $this->respond($pat_rec);
if($requestedModule){
if($requestedModule==1){
$this->modelName = 'App\Models\igmc_pat_1_model';
$pat_rec = $this->model->where('datetime_of_txn >', $formatedDate))->findAll();
return $this->respond($pat_rec);
}
else if($requestedModule==2){
$this->modelName = 'App\Models\igmc_pat_2_model';
$pat_rec = $this->model->where('datetime_of_txn >', $formatedDate)->findAll();
return $this->respond($pat_rec);
}
else{
echo " Data Requested";
}
}
$pat_rec = $this->model->where('datetime_of_txn >', $formatedDate)->where('datetime_of_txn <', $formatedtoDate)->findAll();
return $this->respond($pat_rec);
}
?>
Your just changing the model name not the actual model. Use the model
classmember.
From BaseResource.php
:
/**
* @var string|null The model that holding this resource's data
*/
protected $modelName;
/**
* @var object|null The model that holding this resource's data
*/
protected $model;
Use it like this:
use App\Models\igmc_pat_1_model;
use App\Models\igmc_pat_2_model;
...
if ($requestedModule) {
if ($requestedModule == 1) {
$this->model = new igmc_pat_1_model(); // Change here
$pat_rec = $this->model->where('datetime_of_txn >', $formatedDate)->findAll();
return $this->respond($pat_rec);
} else if ($requestedModule == 2) {
$this->model = new igmc_pat_2_model(); // Change here
$pat_rec = $this->model->where('datetime_of_txn >', $formatedDate)->findAll();
return $this->respond($pat_rec);
} else {
echo " Data Requested";
}
}
Furthermore your code is missing a }
(line 57) and has a )
(line 40) to much.