stibiumz / phalcon.eager-loading

Solves N+1 query problem in Phalcon Model
The Unlicense
36 stars 24 forks source link

Relationship hasManyToMany eager fail when no elements. #5

Open Surt opened 9 years ago

Surt commented 9 years ago

On a hasManytoMany relationship it fails when one of the parent element does not have relationship:

On a model:

        $this->hasManyToMany(
            "id",
            'App\Tag\Models\ElementTag',
            "element_id", "tag_id",
            'App\Tag\Models\Tag',
            "id", array('alias' => 'tags')
        );

When that parent model does not have TagsElements it does fail to fetch the relationship.

 $parentModelResults = Loader::fromResultset($parentModelResults, [
                'tags' => function (QueryBuilder $builder) {
                    $builder->where('App\Tag\Models\ElementTag.element_type = "parentModelType"');
                },
Phalcon\Mvc\Model\Exception: Unknown model or alias 'App\Tag\Models\ElementTag' (1), when preparing: SELECT [App\Tag\Models\Tag].* FROM [App\Tag\Models\Tag] WHERE ([id] IN (:phi0:, :phi1:)) AND (App\Tag\Models\ElementTag.element_type = "playingfield")
stibiumz commented 9 years ago

That's because an extra query is needed to fetch the keys needed to relate tables.

I did not think about it because joining tables are mainly used to build a 'key to key relation' Do you have any suggestion about fixing that?