Hello!
What i have
I have User and Cars models:
class Users extends \Phalcon\Mvc\Model
{
public function initialize() {
$this->hasMany('id', 'Cars', 'ownerId');
}
}
class Cars extends \Phalcon\Mvc\Model {}
Then, if i do this:
$users = Users::query()->limit(10)->execute();
foreach ($users as $user) {
echo "$user->name\n";
foreach ($user->getCars() as $car) {
echo "\t$car->name\n";
}
}
Problem
It works perfectly, but.. in SQL log i see smth like this:
SELECT IF(COUNT(*)>0, 1 , 0) FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_NAME`='users';
DESCRIBE `users`;
SELECT `users`.`id`, `users`.`name` FROM `users` ORDER BY `users`.`id` DESC LIMIT 10 OFFSET 0;
SELECT IF(COUNT(*)>0, 1 , 0) FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_NAME`='cars';
DESCRIBE `cars`;
SELECT `cars`.`id`, `cars`.`name`, `cars`.`ownerId` FROM `cars` WHERE `cars`.`ownerId` = :0;
SELECT `cars`.`id`, `cars`.`name`, `cars`.`ownerId` FROM `cars` WHERE `cars`.`ownerId` = :0;
SELECT `cars`.`id`, `cars`.`name`, `cars`.`ownerId` FROM `cars` WHERE `cars`.`ownerId` = :0;
SELECT `cars`.`id`, `cars`.`name`, `cars`.`ownerId` FROM `cars` WHERE `cars`.`ownerId` = :0;
SELECT `cars`.`id`, `cars`.`name`, `cars`.`ownerId` FROM `cars` WHERE `cars`.`ownerId` = :0;
SELECT `cars`.`id`, `cars`.`name`, `cars`.`ownerId` FROM `cars` WHERE `cars`.`ownerId` = :0;
SELECT `cars`.`id`, `cars`.`name`, `cars`.`ownerId` FROM `cars` WHERE `cars`.`ownerId` = :0;
SELECT `cars`.`id`, `cars`.`name`, `cars`.`ownerId` FROM `cars` WHERE `cars`.`ownerId` = :0;
SELECT `cars`.`id`, `cars`.`name`, `cars`.`ownerId` FROM `cars` WHERE `cars`.`ownerId` = :0;
SELECT `cars`.`id`, `cars`.`name`, `cars`.`ownerId` FROM `cars` WHERE `cars`.`ownerId` = :0;
Question
Yep, lazy load is really cool in some cases. But sometimes it breaks all optimizations. I've read whole tutorial but not found how can i tell ORM to preload some relations in one join-by-index-query?
$users = Users::query()->limit(10)->with('cars')->execute(); // Outer using – disables lazy only for this query
$this->hasMany('id', 'Cars', 'ownerId', ['with' => true]); // Setup-based – disables lazy for this relation forever
And i want to get here JUST ONE sql query. Or, maybe, two.. but not N+1 queries (o.0) cuz selecting 100 users with 10-20 cars will literally kill my database server.
Global
Also, my use-case is to send user data with car data in json string to client (i'm writing api). Maybe, Phalcon has much more better way to do this? Something like to already existed asArray() method but with data from specified relations?
Thank you!