We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Check if relation is loaded

Hi, I was wondering if is it possible to check if a relationship is loaded.

I'm using eager loading and caché so when I'm at a model instance I want to :

  • check if the relationship is loaded,

  • if it's not, then I will try to take it from caché,

  • if not I fetch it using getRelated.

*1 My problem here is that when I try to check if it's null, it automagically loads the relationship, avoiding the caché layer. So, summing up in pseudocode:

public function getMyRelationship()
{
     $cache_key = '....';
     $ttl = 10 * 60;
     if($this->myRelationsip === null) {  // check if the related models are already fetched // *1
              // get from cache or execute function to fetch the related models
              $this->myRelationship = $this->cache->remember($cache_key, $ttl, function() { 
                      return $this->getRelated('myRelationship');
               }
     }

     return $this->myRelationship;  
}


42.1k
edited Apr '17

Hi.

Maybe here is what you're looking for Caching in the ORM

edited Apr '17

Nop :( I just need to check if the relationship is already loaded. So the lazy loading does not fire and I can take it from cache.

The thing is that I could have the relationships loaded using eager load (the relationship is already loaded) and all that models cache documentation only talks about fetching it from database or caché, but it says nothing about checking if it's already loaded.

If I already have a relationship loaded and I call getRelated with caché the system always try to get from cache or fetch from db, never looks if it's already loaded to return the loaded ones.

Hi.

Maybe here is what you're looking for Caching in the ORM

Maybe this is the key:

    if($this->_related['relationshipAlias'] === null) ...