0
votes

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

1

1 Answers

0
votes

I suggest the following explanation:

In the first example findUser() method returns you complete User object. It containts all properties (columns from user db table). So you can access object's properties directly. It also contains some foreign keys (table relations), but there is no need to get data from those tables unless you need it (and it is really reasonably according to db performance).

Result - we have 1 db request(findFirst()).

In the second example you try to access related table data via user object. In this case Phalcon does additional request every time to get data from related table using foreign key (because there is no City information in the User object).

Result - we have 4 db requests (1 request to get User object and 3 requests to get City objects).