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

Best way to retrieve nested manytomany relation objects

Assume the following scenario:

Owners has manyToMany relation with models: Garages and Cars. Garages has a manyToMany relation with Cars as well since each garage can have different cars than the ones from the owner. Now i know how to retrieve the owner's Garages like so:

$owner->getGarages();

The problem is that the Garages do not have the Cars from their manyToMany relation. How can i retrieve the owner's garages and their linked cars?



10.4k

Would you be able to show all the hasManyToMany relationships?



12.1k

What i'm trying to do is list all the current authenticated Owner's Garages with their linked Cars in an overview.



10.4k

I understand what you are looking for but I want to see your code in the three models to make sure you are not missing anything.



12.1k

It's quite a lot of code to post in here, it shouldn't be required to provide an example of the retrieval method for the requested case imho (I am using namespaces when initializing the relations on the models). I did some tests to verify that the relations are in order by retrieving the linked cars from the garages by using:

Garage->getCars();

I am able to retrieve the cars from the garages that way. I just want to know how i can retrieve them by relation, starting off from the owner model.



10.4k

You did put the toManyToMany inside the Garage model, correct? To bind the relationship between all 3 models.

Also you can use:

$cars = $garage->cars;

foreach($cars as $car) { $car->parts; }



12.1k

First of all i apologize to have left this post unanswered for so long. What you're saying works fine but the problem is that the car needs to have his parts initially upon retrieval. When i would call $garage->getCars or $garage->cars, i get the cars without their parts. I need to have these filled in upon retrieval since i'm passing them to my view.

I noticed that there's a new post with someone who's facing the same issue.



26.3k

@scripton

Do you know what will be your strict SQL code of what you want to achive?