Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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: http://localhost/tesis/spm%5contacto/new

How do I access the database in my model?



36.3k
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);