talentify / phalcon.eager-loading
解决 Phalcon 模型中的 N+1 查询问题
4.1.1
2022-08-24 20:22 UTC
Requires
- php: >=7.1
This package is auto-updated.
Last update: 2024-09-25 00:56:54 UTC
README
本软件包为 Phalcon 1.3.* - 2.0.* 提供预加载支持。需要 PHP 5.6,若需支持 PHP 5.3,请使用 php-5.3 分支
支持 Phalcon 3.3
使用方法
使用方法类似于 Laravel,我在 trait 中实现了 with 和 load 方法,因此在一个使用该 trait 的模型(Sb\Framework\Mvc\Model\EagerLoadingTrait)中,您可以这样做
<?php use Sb\Framework\Mvc\Model\EagerLoading\Loader, Sb\Framework\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'); } ]);
有关更多示例和返回类型等,请访问测试文件夹或查看代码,它相当小。