简体   繁体   中英

How to access comments repository by post

I have OneToMany relation between Post and Comment entities.

Now I can easily access comments of a post by using $post->getComments() .

I want to know how can I get these comments ordered in some way or add some custom where conditions to get only specific comments?

I've created a method in CommentsRepository :

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

Is there a possibility to access this method?

I've tried to access it like this: $post->getComments()->findAllOrdered(); , I know that it does not have much sence.

I suppose you need to access it from your Controller

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM