CodeIgniter Forums
CI4 How to load a model by sending params - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: CI4 How to load a model by sending params (/showthread.php?tid=81297)



CI4 How to load a model by sending params - serialkiller - 02-14-2022

I have a controller that loads a model and I need to pass parameters
PHP Code:
namespace App\Controllers;


class 
Utenti_interni extends BaseController
{
    private $query_add$final_query$sql;


    public function __construct()
    {
        $this->Mymodel model('App\Models\Mymodel');

    }



How can I send parameters to the model?
I tried with:

PHP Code:
$this-Mymodel model('App\Models\Mymodel'true, ['123''abc']); 
But it does not work


RE: CI4 How to load a model by sending params - demyr - 02-14-2022

On top of your controller call your Model
PHP Code:
use App\Models\YourFolderNameForModels\UsersModel//for example user models 


You can call it in your __construct like you did, but be careful:

PHP Code:
$this->UserModel = new UsersModel(); 

Then you can use it :

Code:
$data = [
'name' => $name_from_the_form,
'surname' => $surname_from_the_form
];

$result = $this->UsersModel->lets_do_something($data);



RE: CI4 How to load a model by sending params - serialkiller - 02-14-2022

(02-14-2022, 04:50 AM)demyr Wrote: On top of your controller call your Model
PHP Code:
use App\Models\YourFolderNameForModels\UsersModel//for example user models 


You can call it in your __construct like you did, but be careful:

PHP Code:
$this->UserModel = new UsersModel(); 

Then you can use it :

Code:
$data = [
'name' => $name_from_the_form,
'surname' => $surname_from_the_form
];

$result = $this->UsersModel->lets_do_something($data);

So yes, I would like to pass parameters to the class instantiation using
PHP Code:
model('mymodel'); 



RE: CI4 How to load a model by sending params - paulbalandan - 02-14-2022

Sadly, you can't. `model()`'s 2nd and 3rd parameters are fixed to accept instances of ConnectionInterface and ValidationInterface.
https://github.com/codeigniter4/CodeIgniter4/blob/b36b015ac4e326df83d48182a2eed4512828050a/system/Common.php#L809-L812


RE: CI4 How to load a model by sending params - kenjis - 02-15-2022

2nd parameter is $getShared.
3rd parameter is ConnectionInterface.

Do you want to do like this?
Mymodel does not extend CodeIgniter\Model.

PHP Code:
$this->Mymodel = new \App\Models\Mymodel('123''abc');