elcreator / phalcon.eager-loading
解决 Phalcon 模型中的 N+1 查询问题
dev-master
2021-12-05 20:19 UTC
Requires
- php: >=7.2
- ext-phalcon: >=4
This package is auto-updated.
Last update: 2024-09-29 06:09:12 UTC
README
此包为 Phalcon 4.* - 5.* 提供懒加载支持。需要 PHP 7.2
用法
如 https://github.com/phalcon/incubator#autoloading-from-the-incubator 中所述,自动加载该特质
用法与 Laravel 类似。通过特质 with 和 load 方法实现,因此在一个使用该特质的模型(\Phalcon\Mvc\Model\EagerLoadingTrait)中,你可以做
<?php use \Phalcon\Mvc\Model\EagerLoading\Loader, \Phalcon\Mvc\Model\EagerLoading\QueryBuilder; $robotsAndParts = Robot::with('Parts'); // Equivalent to: $robots = Robot::find(); foreach ($robots as $robot) { $robot->parts; // $robot->__get('parts') } // Or $robot = Robot::findFirst()->load('Parts'); // Equivalent to: $robot = Robot::findFirst(); $robots->parts; // $robot->__get('parts') // Because Robot::find() returns a resultset, so in that case this is solved with: $robots = Loader::fromResultset(Robot::find(), 'Parts'); # Equivalent to the second example // Multiple and nested relations can be used too $robots = Robot::with('Parts', 'Foo.Bar'); // And arguments can be passed to the find method $robots = Robot::with('Parts', 'Foo.Bar', ['limit' => 5]); // And constraints $robots = Robot::with( [ 'Parts', 'Foo.Bar' => function (QueryBuilder $builder) { // Limit Bar $builder->limit(5); } ], [ 'limit' => 5 ] ); // constraints with the Loader too $robots = Loader::fromResultset(Robot::find(), [ 'Foo.Bar' => function (QueryBuilder $builder) { $builder->where('Bar.id > 10'); } ]);
更多示例和返回类型等请访问测试文件夹或查看代码,它相当小。