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.

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() {}


13.3k
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');
    }
}


688

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'); } } ```