简体   繁体   中英

Phalcon hasManyToMany data load very slow

I have a problem with load slow dates from model with hasManyToMany.

I have code:

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';
  }
}

Table Tvguide have more records (1kk+), but TvguideChannel have 228 records

When I Want output records from table TvguideChannel with:

$data = TvguideChannel::find();

I get load page more 5 seconds. How I can output all records correctly with relation hasManyToMany?

You can fix this by using eager loading instead. The incubator allow this, just include it into your project and use the "with" instead of "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
    ]
);

Distributed as single package at https://github.com/stibiumz/phalcon.eager-loading

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM