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

Possible bug in ORM?

I have two Phalcon\Mvc\Model (Users, Cities). Every user has a city, so the Users model has a hasOne relationship (alias = City).

$User = Users::findFirst($user_id);
$name = $User->name;
$name = $User->name;
$name = $User->name;

The above code is ok, because Phalcon runs only one query to the database.

$User = Users::findFirst($user_id);
$city = $User->City->name;
$city = $User->City->name;
$city = $User->City->name;

The above code runs 3 query. Everytime I try to get a value from Cities Phalcon runs the same query again. Why?

Phalcon 1.3.2
PHP 5.5.9
PostgreSQL 9.3.4

I think $User->City should be inited (filled with data) at the first time I try to access it and then kept in memory. We are in the process of changing from Kohana framework to Phalcon. The ORM system of Kohana works like this and we loved it.



98.9k
Accepted
answer

You have to define the relation as 'reusable' to obtain the records as you want. https://docs.phalcon.io/en/latest/reference/models-cache.html#reusable-related-records

Oh, I see, thanks. We were stucked at the "Working with Models" section of the docs and that not mentioned this. A grid with available relation options (alias, reusable, etc) could be helpful there. Anyway, thanks four your help!



2.5k

Thanks! Can it be set globally?

\Phalcon\Mvc\Model::setup does not support it.

Any other way?



98.9k

No, it cannot be set globally, you have to pass that option to every relation definition