CodeIgniter Forums

Full Version: Help me to create Models CI4
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, there!

I want to create some MyModel inside app/Models directory, I have followed CI4 docs. But I got this error :

Code:
Too few arguments to function App\Models\MyModel::__construct(), 0 passed in C:\xampp\htdocs\project-name\my.project-name.tld\acme\Home

I have tried like this in BaseController (because I am using hmvc) :

Code:
// Load Database
$this->database = \Config\Database::connect();

// Load MyModel
$this->myModel  = new \App\Models\MyModel($this->database);

But still got same error, maybe I miss understand? Thanks Smile
Try this one and see if it works for you.

PHP Code:
class UserModel
{
    protected $db;

    public function __construct(ConnectionInterface &$db null)
    {
        if ($db instanceof ConnectionInterface)
        {
            $this->db =& $db;
        }
        else
        {
            $this->db Database::connect($this->DBGroup);
        }
    }

(02-04-2020, 06:02 AM)InsiteFX Wrote: [ -> ]Try this one and see if it works for you.

PHP Code:
class UserModel
{
    protected $db;

    public function __construct(ConnectionInterface &$db null)
    {
        if ($db instanceof ConnectionInterface)
        {
            $this->db =& $db;
        }
        else
        {
            $this->db Database::connect($this->DBGroup);
        }
    }


It still not working as well, here the error

Code:
Class 'App\Models\Database' not found

I have tried

Code:
$this->db = \Database::connect($this->DBGroup);

Still not working. I have checked my db config, nothing I miss with that.

This script try to connect database in app\Config\Database, isn't?

Code:
$this->db = Database::connect($this->DBGroup);

Here is my full script, after got suggestion from InsiteFX

PHP Code:
<?php namespace App\Models;

use 
CodeIgniter\Database\ConnectionInterface;

class 
MyModel
{

    protected $db;

    public function __construct(ConnectionInterface &$db null)
    {
        if ($db instanceof ConnectionInterface)
        {
            $this->db =& $db;
        }
        else
        {
            $this->db Database::connect($this->DBGroup);
        }
    }


Try one of these.

PHP Code:
$this->db Database::connect();

// or
$this->db Database::connect($this->default); 

A convenience method exists that is purely a wrapper around the above line and is provided for your convenience:


PHP Code:
$db db_connect(); 
(02-04-2020, 01:08 PM)InsiteFX Wrote: [ -> ]Try one of these.

PHP Code:
$this->db Database::connect();

// or
$this->db Database::connect($this->default); 

A convenience method exists that is purely a wrapper around the above line and is provided for your convenience:


PHP Code:
$db db_connect(); 

the helper its working for me, great!