This site has been archived and you can no longer log in or post new messages. For up-to-date community resources please visit

eZ Community » Forums » eZ Publish 5 Platform » How to get a related object?

How to get a related object?

How to get a related object?

Tuesday 27 May 2014 5:51:50 pm - 4 replies

Hi there,

I have created a custom content type named "Page" with a related "Image" object from the media library.

I'm wondering what is the best way to get this related object in a template.

For now, what I did is a custom controller with a custom query to get the object based on the id from the main content object. The image object is available in the template with its own variable. It works pretty well.

But what if I have a loop of page object and need to get the related image object? With the method described above I can't attach the image to the main object and it's going to be heavy in queries.

I tried the loadRelations and loadReverseRelations methods ContentService repository but I'm not sure about it.

The first one don't give me the image object and the second one says the user don't have permissions to use it. I'm confused.

Can I join object the Doctrine way with the search service maybe?  

Thanks for your help 

Modified on Wednesday 28 May 2014 11:26:54 am by Julien Huon

Wednesday 28 May 2014 2:06:03 pm

Hi Julien

maybe this gist helps you. It shows a sample frontpage controller which picks a random banner image from a list of related objects. It would be easy to adopt it to return an array of content objects to be displayed in the TWIG template.


Wednesday 28 May 2014 5:59:52 pm

Thank you very much Donat, it's works great! Not sure what I was doing wrong.

Instead of having a separated query for the related content, do you know if it's possible to access related content directly from $content? Something like $content->related or $content->getRelated('image')?

Wednesday 28 May 2014 6:32:17 pm

No, this is not possible as the services usually return a simple read-only ValueObject with no intelligence. This is due to the separation of concerns of the MVC paradigm which may seem cumbersome at first sight, but has many advantages.

A tip for development: if you use an intelligent IDE (like PhpStorm) then you can get insight (and speed up typing) by declaring the exact type of variables as in lines 6 and 19 in the gist above.

Monday 02 June 2014 4:23:12 pm

Thanks for your help Donat.


You must be logged in to post messages in this topic!

36 542 Users on board!

Forums menu

Proudly Developed with from