I
I
Ilya Loopashko2020-09-28 13:09:23
symfony
Ilya Loopashko, 2020-09-28 13:09:23

How to display data from two tables?

There is a table with Post records. There is a table with Tag. There are several Tags for each Post entry. how to display tags for each post?

And then for each record the total number of Tag records is displayed.

5f71b6122bb0c409008814.png

{% for posts in post %}
            <div class="row border-bottom pb-2 pt-2">
                <div class="col-md-3"><img src="{{ vich_uploader_asset(posts) }}" class="d-flex mr-3 img-thumbnail" alt="{{ posts.thumbnailFile }}"></div>
                <div class="col-md-9 pt-2">
                    <h4 class="mt-0 font-weight-bold"><a href="{{ path('single', {'post': posts.id }) }}">{{ posts.title }}</a></h4>
                    <p class="mb-0"><small><i class="far fa-calendar-alt pr-2"></i>{{ posts.createdAt|date("F jS \\a\\t g:ia") }}</small></p>
                    <a href="#" class="btn btn-primary btn-sm active mt-4" role="button" aria-pressed="true">{{ posts.category }}</a></br>
                    {% for tags in tag %}
                        <a href="#" class="btn btn-primary btn-sm active mt-4" role="button" aria-pressed="true">{{tags}}</a>
                    {% endfor %}
                </div>
            </div>
        {% endfor %}


Code from controller
<?php

namespace App\Controller;

use App\Entity\Category;
use App\Entity\Menu;
use App\Entity\Post;
use App\Entity\Tag;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

class DefaultController extends AbstractController
{
    /**
     * @Route("/default", name="default")
     */
    public function index()
    {
        $em = $this->getDoctrine()->getManager();
        $post = $em->getRepository(Post::class)->findAll();
        $menu = $em->getRepository(Menu::class)->findAll();
        $category = $em->getRepository(Category::class)->findAll();
        $tag = $em->getRepository(Tag::class)->findAll();


        return $this->render('default/index.html.twig', [
            'controller_name' => 'DefaultController',
            'post'=>$post,
            'category'=>$category,
            'tag'=>$tag,
            'menu'=>$menu

        ]);
    }

    /**
     * @Route("/post/single/{post}", name="single")
     */
    public function single(Post $post)
    {
        return $this->render('default/single.html.twig', [
            'post'=>$post

        ]);
    }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
montray, 2020-09-28
@deadloop

{% for tag in post.tags %}
You yourself take all the tags from the database and render in each post, but you need related ones.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question