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

How do I access the database in my model?

run a simple query on a model I want to call a sql query within a function in my model

public function afterCreate() {

    $sql="SELECT SQC_AUDITORIA.NEXTVAL as CODIGO FROM DUAL";
    $robot = $this->db->fetchOne($sql);

            $auditar = new Auditoria();

            $request = $this->getDI()->getRequest();
            $auditar->AUD_ID=$robot["CODIGO"];
            $auditar->AUD_MODELNAME = $this->CONT_CEDULA;
            $auditar->AUD_IPADRESS = $request->getClientAddress();
            //$auditar->AUD_OLDVALUE = $originalData[$field];
            $auditar->save();
            if ($auditar->save() == false) {
                foreach ($auditar->getMessages() as $message) {
                    echo $message, "\n";
                }
            }
        }

But I have the following error

[Tue Jun 14 22:52:00.287215 2016] [:error] [pid 31052] [client 127.0.0.1:25757] PHP Notice: Access to undefined property SpmContacto::db in /var/www/html/tesis/app/models/SpmContacto.php on line 231, referer: https://localhost/tesis/spm_contacto/new

How do I access the database in my model?



58.4k
Accepted
answer

Hello

You should access database via DI, so you need change this line

    $robot = $this->db->fetchOne($sql);

Tobe

    $robot = $this->getDI()->get('db')->fetchOne($sql);