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

Huge number of SQL queries per page load

So Phalcon is nice with its level of abstraction that "hides" sql queries to the level that we can forget we even use them. But when I actually checked how much queries one of my pages executes when loading paginated records (100 per page) the result was around 500... The queries were generated mostly due to simple relations (belongsTo / hasMany in model) because for every record i must fetch some details from another models. Is that many queries "normal"? Or should I find another way for loading my records, for example with multiple joins?

What metadata adapter you are using ? Are you using query builder ? If not - start using it. It's like any other orm - if you don't do join, then framework will need to make queries. For example let's assume you have 1-n relation. Categories have products. For example we have 100 categories, each having 500 queries. If we don't make joins then we need 100 additional queries for each category to get their products.

I load most of the data with query builder and then i use model relations with params. For example i load some messages and then for every message i display author nickname only when he is "active user" (using relation with alias ActiveUser). if i had to use only builder for that, then i will have to join User table with a appriopriate condition. but then i can't store logic for what makes an active user nicely in relation param :(

Class Phalcon\Mvc\Model represents the implementation of ActiveRecord (ORM), that's what it is under the hood.

So at the end of the day, RDBMS will be the culprit in each application. That's why I try to avoid as much as I can any ORM out there. When I see 100's of queries instead of 2-3... but that's what it is with ORM.

Then as i wrote - try to use query builder more to select author nickname with join/group_concat or something. This is normal thing and will happen in all orm.