문제

I have the tables as follows: structure -> OneToMany -> media media -> ManyToOne -> typeMedia

Browsing structure must enter the media for every type.

For example:

Photo:

img, img, img, img ..

Video:

video, video, video ...

...

I tried in every way, a for loop inside another for loop, but typeMedia (photo, video ..) are duplicated forever..

Here the code, but it is wrong

{% for media in structure.media %}
      {% for type in media.typeMedia.media %}
            <h3>{{ type.typeMedia.name }}</h3>
            <hr/>
            <img src="{{ type.webPath | imagine_filter('thumb', true) }}" />
      {% endfor %}
{% endfor %}

How can I fix?

I need to change the database structure?

도움이 되었습니까?

해결책

Firstly, I am guessing that in your twig code type.webPath that should be media.webPath? As it doesn't make sense for webPath to be an attribute of the media type?

The database structure is fine. However, you cannot directly follow the relationship typeMedia.media to get the results for a single structure. The typeMedia.media relationship will always give you all media of that type (for all structures), regardless of how you navigated to the typeMedia. Furthermore, as long as your outer loop is iterating over a set of media, it is only possible to output by mediaType from twig if that set of media is already ordered by mediaType. This is not the case by default when using structure.media.

There are various ways you could do this. One way would be to add a method to your Structure entity class to get the media by type. The advantage of this approach is that it enables you to get the media by type for a structure from anywhere in your code - repository, service, controller or twig. For example:

In your Structure entity class:

public function getMediaByTypeName()
{
    $mediaByType = array();

    foreach ($this->media as $aMedia)
    {
        $typeName = $aMedia->getTypeMedia()->getName();
        if (!array_key_exists($typeName, $mediaByType)) $mediaByType[$typeName] = array();
        $mediaByType[$typeName][] = $aMedia;
    }

    return $mediaByType;
}

In your twig:

{% for typeName, media in structure.mediaByTypeName %}
    <h3>{{ typeName }}</h3>
    <hr/>
    {% for aMedia in media %}
       <img src="{{ aMedia.webPath | imagine_filter('thumb', true) }}" />
    {% endfor %}
{% endfor %}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top