Load Relations of a model on find()

Hi all,

I have a model with relationship with other models. I want to load related data when I call find() nethod on this method, so that I dont call related setter for each record. Is there any option to include joins to query?

Best Regards, Hasan Gharehasanloo


As far as I understand, the default behaviour is quite similar, since when you retrieve related data they are implicitly fetched from database. http://docs.phalcon.io/en/latest/reference/models.html#taking-advantage-of-relationships

edited Oct '14

Hi! You can use something like this:

// News Model:

// ...

public function getCategory()
        return $this->category_id;        

public function getRelatedCategory() 
        return \Category\Model\Category::findFirst($this->getCategory());

// ...

// Somewhere in yur project:

$newsEntity = News::findFirst($id);
$categoryEntity = $newEntity->getRelatedCategory();

There are 2 DB queries, but useful


Thanks Benoit & Oleksandr Base on Oleksandr sample, I dont want to fetch News by findFirst(), I want a collection of News by find(). In this case I sholud fetch related categories in a foreach senetence, and it will multiply db queries by count of News. In fact I want to fetch related categories in the same db query when I am fetching News. I asked this questio because there is such a functionality in Laravel . you can find it at http://laravel.com/docs/eloquent#eager-loading link.

Best Regards Hasan Gharehasanloo


Hey guys,

I think this would be quite easy to implement by overriding the find / findFirst methods, as per http://docs.phalcon.io/en/latest/reference/models-cache.html#overriding-find-findfirst or creating their alternatives (findRelated or something)

Instead of running the default ones, just create a PHQL query with a join inside. This should work as long as you only want to read the received data.