Symfony显示最新帖子(当前已打开)

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

zhoulang914 回答:Symfony显示最新帖子(当前已打开)

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

  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. 如果在存储库实体中使用查询生成器,则可以添加“ exclude”参数:

操作:

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','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()
    }
}
本文链接:https://www.f2er.com/3151512.html

大家都在问