Search code examples
modeldatabase-connectioncodeigniter-4

CI4 - Can't connect to a custom database


I don't understand. I'm trying to use a model with a custom database connection (https://codeigniter4.github.io/userguide/models/model.html#accessing-models)...but CI4 doesn't take it. CI4 is only considering the defaultDB set in Config/Database.

My custom connection is ok, it is sure. Direct queries work fine. The problem appears only if I call my model class.

My controller script:

                $custom = [
                    'DSN'      => '',
                    'hostname' => 'myhostname',
                    'username' => 'myusername',
                    'password' => 'mypassword',
                    'database' => 'mydatabase',
                    'DBDriver' => 'MySQLi',
                    'DBPrefix' => '',
                    'pConnect' => false,
                    'DBDebug'  => (ENVIRONMENT !== 'production'),
                    'charset'  => 'utf8',
                    'DBCollat' => 'utf8_general_ci',
                    'swapPre'  => '',
                    'encrypt'  => false,
                    'compress' => false,
                    'strictOn' => false,
                    'failover' => [],
                    'port'     => 3306,
                ];
                
                $db = \Config\Database::connect($custom);
                
                
                $basedd=model('App\Models\Users',true, $db);
                print_r($basedd->findAll());

My model:

namespace App\Models;

use CodeIgniter\Model;

class Users extends Model
{
    protected $table = 'users';
    public $primaryKey;
    protected $allowedFields;
    function __construct()
    {
        $this->primaryKey='id';
    }
}

It returns:

mysqli_sql_exception #1146 Table 'mydefaultdb.users' doesn't exist


Solution

  • The problem here is that you're changing the construct in your model.

    Change your model to:

    namespace App\Models;
    
    use CodeIgniter\Model;
    
    class Users extends Model
    {
        protected $table = 'users';
        public $primaryKey = 'id';
        protected $allowedFields;
    }
    

    If you check the base code for the codeigniter model construct $db should be the first param and validation the second. You're removing both in your construct.

     public function __construct(?ConnectionInterface $db = null, ?ValidationInterface $validation = null)
     {
            /**
             * @var BaseConnection|null $db
             */
            $db ??= Database::connect($this->DBGroup);
    
            $this->db = $db;
    
            parent::__construct($validation);
     }
    

    Never change the construct structure.