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

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



1.9k

As far as I understand, the default behaviour is quite similar, since when you retrieve related data they are implicitly fetched from database. https://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



1.7k

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 https://laravel.com/docs/eloquent#eager-loading link.

Best Regards Hasan Gharehasanloo



15.1k

Hey guys,

I think this would be quite easy to implement by overriding the find / findFirst methods, as per https://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.