stibium / phalcon.eager-loading
解决 Phalcon 模型中的 N+1 查询问题
dev-master
2015-06-26 15:20 UTC
Requires
- php: >=5.6
- ext-phalcon: 1.3 - 2.0
This package is not auto-updated.
Last update: 2024-09-28 17:38:23 UTC
README
此包为 Phalcon 1.3.* - 2.0.* 提供预加载支持。需要 PHP 5.6,若要支持 PHP 5.3,请使用 php-5.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'); } ]);
更多示例和返回类型等,请访问测试文件夹或查看代码,它相当小巧。