如何通过 post 访问评论存储库

How to access comments repository by post

我在 Post 和 Comment 实体之间有 OneToMany 关系。

现在我可以使用 $post->getComments().

轻松访问 post 的评论

我想知道如何以某种方式对这些评论进行排序或添加一些自定义 where 条件以仅获取特定评论?

我在 CommentsRepository 中创建了一个方法:

public function findAllOrdered()
    {
        return $this->createQueryBuilder('c')
            ->orderBy('c.created_at', 'DESC')
            ->getQuery()
            ->getResult()
        ;
    }

是否有可能访问此方法?

我试过这样访问它:$post->getComments()->findAllOrdered();,我知道它没有多大意义。

我想你需要从你的控制器访问它

use AppBundle\Entity\Comment;

public function listComments()
{
    $comments = $this->getDoctrine()
        ->getRepository(Comment::class)
        ->findAllOrdered();
}
class PostRepository extends EntityRepository
{

    private $em;

    public function __construct(EntityManagerInterface $em, Mapping\ClassMetadata $class)
    {
        parent::__construct($em, $class);
        $this->em = $em;
    }

    /**
     * @param null $sql
     * @param array $params
     * @return array
     * @throws \Exception
     */
    public function findAllPostUserCommentEtcWhatEverYouWant($sql = null, $params = [])
    {
        try {
            return $this->em->getConnection()->executeQuery($sql, $params)->fetchAll();
        } catch (DBALException $e) {

        }
        throw new \Exception('');
    }

    /**
     * @return array
     */
    public function findThis()
    {
        try {
            return $this->findAllPostUserCommentEtcWhatEverYouWant('select .  ..');
        } catch (\Exception $e) {
        }
    }

    /**
     * @return array
     */
    public function findThat()
    {
        try {
            return $this->findAllPostUserCommentEtcWhatEverYouWant('select .  ..');
        } catch (\Exception $e) {
        }
    }




    /**
     * @Route("/pdo", name="pdo")
     */
    public function pdo(EntityManagerInterface $em)
    {
        $result = $em->getRepository(Post::class)->findThat();
        $result = $em->getRepository(Post::class)->findThis();