We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Query not executing because of $this object

When I am executing I am getting error in Model Object.

Fatal error: Uncaught Error: Using $this when not in object context in index.php(File is in Model folder).

Query I am using '$result = $this->connection->query('select * from course');'

Thanks in Advance.

  1. You are not in object context, so $this will not work;
  2. You need to get connection service from DI, to execute your request.

Hi janisbizkovski. How could I get the connection from DI?. In services.php I have all the code for connection object

$di->setShared('db', function () { $config = $this->getConfig();

$class = 'Phalcon\Db\Adapter\Pdo\\' . $config->database->adapter;
$params = [
    'host'     => $config->database->host,
    'username' => $config->database->username,
    'password' => $config->database->password,
    'dbname'   => $config->database->dbname,
    'charset'  => $config->database->charset
];

if ($config->database->adapter == 'Postgresql') {
    unset($params['charset']);
}

$connection = new $class($params);

return $connection;

});



3.3k
Accepted
answer
edited Aug '17

Hi @Karthik26119 ,

please reference to https://docs.phalcon.io/en/3.2/tutorial-base as it's clearly visible from your code, that you are missing complete basics of MVC, DI e.t.c.

Answering to your question:

  1. You need to make sure, that you have registered services from your services.php file

  2. I don't see anywhere, that you have registered service connection

  3. To access db service(the one you have registered) from anywhere, you can call \Phalcon\Di::getDefault()->get("db"), but make sure, that point 1. is done to do this.

Hi @janisbizkovski. Thank you for the suggestion. I got the connection object after I used the below line in Model object

$connection = Di::getDefault()->get("db");

JUst want you to know that I already registered the db service on Services.Php. By using the above line by your reference I got the output.

Thank you. You saved my time :)

Why you even need to get di and get db service in model? What's a problem with query builder or built-in methods in model or Model::query?