Symfony显示最新帖子,但当前未打开

问题描述 投票:-3回答:1

我有一个呈现最新帖子的模板。如果我从他们那里打开一个帖子,它仍在显示。我要么需要从URL获取当前打开的帖子的ID,要么以某种方式在控制器或查询生成器中过滤帖子。我暂时不会提供任何代码,因为我不知道您需要什么帮助。如果需要,请询问其他代码。谢谢

symfony url get unique id
1个回答
1
投票

这取决于您如何获得最新帖子。有几种可能。

  1. 您可以在树枝视图中过滤:

动作:

public function viewPost(Request $request, EntityManager $em): Response
{

    $postId = $reqeust->get('id');
    $post = $em->getRepository(Post::class)->find($postId);
    $newestPosts = $em->getRepository(Post::class)->findAll();

    return $this->render('Post/view.html.twig', [
        'post'          => $post,
        'newestPosts'   => $newestPosts
    ]);
}

视图:

{% for newPost in newestPosts if newPost.id != post.id %}
<h2>{{ newPost.title}}</h2>
{% endfor %}
  1. 如果您在存储库实体中使用查询生成器,则可以添加“排除”参数:

动作:

public function viewPost(Request $request, EntityManager $em): Response
{

    $postId = $reqeust->get('id');
    $post = $em->getRepository(Post::class)->find($postId);
    $newestPosts = $em->getRepository(Post::class)->findNewPosts(7, $postId);

    return $this->render('Post/view.html.twig', [
        'post'          => $post,
        'newestPosts'   => $newestPosts
    ]);
}

存储库:

<?php

namespace App\Repository;

use App\Entity\Post;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\Query\Expr;
use Symfony\Bridge\Doctrine\RegistryInterface;

/**
 * ProductRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PostRepository extends ServiceEntityRepository
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, Product::class);
    }

    public function findNewPosts($days, $postId)
    {
        $date = new \DateTime();
        $date->modify('-'.$days.' day');

        $query = $this->createQueryBuilder('p');

        return $query->where('p.id <> :requestPost')
            ->andWhere('p.datetime >= :requestDatetime')
            ->setParameter('requestProduct', $postId)
            ->setParameter('requestDatetime', $date);
            getQuery()->getResult()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.