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.

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.



81.3k
Accepted
answer

You have to define the relation as 'reusable' to obtain the records as you want. http://docs.phalconphp.com/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!



1.8k

Thanks! Can it be set globally?

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

Any other way?



81.3k

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