How does Phalcon\Mvc\Model::findRelated() work with DB?

Hi,

Question for Phalcon developers...

If I have a model relationship set-up in a one-to-many fashion (One Writer, 5 Books) and fetch related Book models with

$author->findRelated('Books');

how many times does Phalcon hit DB internally?

Thanks!



8.4k

Hi temury416! I do not know the exact amount of db interaction but you could add an event handler to the db object to log these interactions. In the following code the log file "db.log" is stored in the app/logs/ folder. You can change it if you want or you have to create the logs folder.

$di->set('db', function() use ($config) {

    $connection =  new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        'host' => $config->database->host,
        'port' => $config->database->port,
        'username' => $config->database->username,
        'password' => $config->database->password,
        'dbname' => $config->database->dbname,
        'options' => [
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
            PDO::ATTR_EMULATE_PREPARES  => false,
            PDO::ATTR_STRINGIFY_FETCHES => false,
        ]
    ));

    $eventsManager = new Phalcon\Events\Manager();

    $logger = new Phalcon\Logger\Adapter\File("../app/logs/db.log");

    /**
     * Listen all the database events
     */
    $eventsManager->attach('db', function($event, $connection) use ($logger) {
        if ($event->getType() == 'beforeQuery') {
            $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO);
        }
    });
    $connection->setEventsManager($eventsManager);
    return $connection;
});

Best regards

First off, there is no findRelated() function that I could find. You would do a php $author->findBooks(); to get the books. Looking through the code for 2.0, which is a little easier to understand for me, it looks like there is only one query performed. Basically it gets the related model (Books in this case) and does a find() based on the value of the relation column. Basically it's the equivalent of:

$books = Books::find('author_id = ' . $author->id);


7.2k

You'll have N+1 request query from Mysql on related model, if you describe model with public properties. And you'll have 2 request query, if your choice is model with getters/setters. See http://forum.phalconphp.com/discussion/1438/models-relationships-vs-join