我遇到来自hasManyToMany模型的加载慢日期的问题。
我有代码:
class TvguideChannel extends Model{
public function initialize() {
$this->setSource('tvguide_channel');
$this->setConnectionService('db');
$this->hasManyToMany(
'code',
__NAMESPACE__.'\Tvguide',
"ch_code",
'ch_code',
__NAMESPACE__.'\Chgrtv',
'ch_code',
['alias' => 'tvguide']
);
//$this->hasMany('code', __NAMESPACE__.'\Chgrtv', 'ch_code', ['alias' => 'tvgg']);
}
public function getSource() {
return 'tvguide_channel';
}
}
表Tvguide有更多记录(1kk +),但TvguideChannel有228条记录
当我想从表TvguideChannel输出记录时:
$data = TvguideChannel::find();
我的加载页面超过5秒。 如何使用关系hasManyToMany正确输出所有记录?
答案 0 :(得分:0)
您可以通过使用预先加载来解决此问题。孵化器允许这样做,只需将其包含在您的项目中并使用“with”而不是“find”。
composer require phalcon/incubator
https://github.com/phalcon/incubator/tree/master/Library/Phalcon/Mvc/Model
<?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
]
);
分发为单个包