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

get reference to db connection on model phalcon

How do i get access to the database via the model. I'm extending a class from model class which on initialize will set a property to the connection. This is my code:

    <?php
    use Phalcon\Mvc\Model;
    class BaseModel extends Model
    {
        protected $db;

        public function initialize()
        {
            $this->db = $this->getDi()->getShared('db');
        }
    }

it works on a controller class but not here. Any help

edited Nov '15

I'm using these methods:

    /**
     * Returns the models manager related to the entity instance
     *
     * @return \Phalcon\Mvc\Model\ManagerInterface 
     */
    public function getModelsManager() {}

    /**
     * Gets the connection used to read data for the model
     *
     * @return \Phalcon\Db\AdapterInterface 
     */
    public function getReadConnection() {}

    /**
     * Gets the connection used to write data to the model
     *
     * @return \Phalcon\Db\AdapterInterface 
     */
    public function getWriteConnection() {}


21.5k
Accepted
answer

Maybe this is what you want:

<?php
use Phalcon\DI;
use Phalcon\Mvc\Model;

class BaseModel extends Model
{
    protected $db;

    public function initialize()
    {
        $this->db = DI::getDefault()->get('db');
    }
}


1.5k

You can also get the database connection within a model's method like this:

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

This will work, but only if you have one DI in your project. While most of the time that's sufficient, this is is slightly better ;]

public function initialize() {
    $this->db = $this->getDI()->get('db');
}

Maybe this is what you want:

<?php
use Phalcon\DI;
use Phalcon\Mvc\Model;

class BaseModel extends Model
{
   protected $db;

   public function initialize()
   {
       $this->db = DI::getDefault()->get('db');
   }
}