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 object and belonging object with only one query

I have an ORM optimization problem. Let's say I want to retrieve a RobotsParts object and its associated Robots object with ONLY one query. I don't want arrays, only objects.

I tried to do that, inside a function of the RobotsParts model class:

$part = self::query()
    ->columns('Namespace\Models\RobotsParts.*, Namespace\Models\Robots.*')
    ->join('Namespace\Models\Robots')
    ->where('Namespace\Models\RobotsParts.id = :id:')
    ->bind(array(
        'id' => 1
    ))
    ->execute()
    ->getFirst()
;

The following query is executed, which is totally what I want. I simplified it so it's easy to read:

SELECT robotsparts.*, robots.* FROM robotsparts INNER JOIN robots ON robotsparts.robots_id = robots.id WHERE robotsparts.id = 1;

My first problem after that, is that I don't get directly a RobotsParts object, but a Phalcon\Mvc\Model\Row object. I managed to obtain a RobotsParts by doing this, is it correct ?

$part = $part['Namespace\Models\RobotsParts'];

Anyway, my biggest problem is that when I do that :

$robot = $part->robots;

Another query to get the robot is launched, which is totally useless since the associated robot was already joined is the first query.

Am I missing something here? Is there another way to do that (querybuilder, etc.) ? Thank you for your help. By the way, Phalcon is an amazing framework.

Yes, i think i get what u want and need. So, the answer is called "Eager Loading" ...but the problem is- it is not implemented in phalcon yet. I think i read in blog... yes:

Coming soon

In the future 2.0.x series, we will be concentrating our efforts on requests from the community:

Eager-Loading in PHQL

Optional string empty values in the ORM

PHQL custom functions

Case Statements in PHQL

Aliases for namespaces in PHQL

So... soon u can do what u need :P me too :P

Greetings!

here is the library for eager loading that you can use until phalcon team will implement it https://github.com/stibiumz/phalcon.eager-loading