Thanks jodator,
But it is a little bit different that I needed. I wanted to execute sql queries from the Model.
After spending more time testing and experimenting I think I figured it out. Just in case if someone has the same need to be able execute mysql queries from the model, here the way I figured it out. I'm not sure if impacts the performance, but it works.
Create a new Model class and call it for example BaseModel.php with the next inside:
class BaseModel extends Phalcon\Mvc\Model
{
public $db;
public function initialize()
{
$this->db=$this->getDi()->getShared('db');
}
}
The BaseModel will extend the Phalcon Model and I created a public property called $db. Then on the initialize() I used $this->getDi()->getShared('db') to grab shared dependency injector and assigned it to our $this->db. Now all Models that extend this BaseModel will have access to that property. Then in my Users Model I have next:
class Users extends BaseModel // Users extends out BaseModel and will have access to $db
{
public function test()
{
//print_r(\Phalcon\Di::getDefault()->getShared('db')); // This is the ugly way to grab the connection.
$result=$this->db->query("SELECT * FROM phalcon.system_users"); // Working now
echo $result->numRows();
print_r($result->fetchAll());
}
}
Now it works beautifully. I also figured out one more thing that might be interesting to someone who wants to use mysql queries (PDO) in Phalcon. I always use FETCH_ASSOC when fetching data, and to make life easier you can set up FETCH_ASSOC by default at the connection this way you don't need to setAttribute every time fetching data. Here is how I have done it. At the bootstrap, when setting DI class for the database connection, you can include the options....
//Setup the database service
$di->set('db', function(){
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => "localhost",
"username" => "root",
"password" => "123456",
"dbname" => "",
'options' => [PDO::ATTR_CASE => PDO::CASE_LOWER, PDO::ATTR_PERSISTENT => TRUE,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC],
));
});
As you see the last option sets PDO::ATTR_DEFAULT_FETCH_MODE.
If anyone has better way to do that, please post it here.
I hope it will help newbies to Phalcon like me :)