[英]How to access comments repository by post
I have OneToMany
relation between Post and Comment entities. 我在Post和Comment实体之间有OneToMany
关系。
Now I can easily access comments of a post by using $post->getComments()
. 现在,我可以使用$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
: 我已经在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();
我试图这样访问它: $post->getComments()->findAllOrdered();
, I know that it does not have much sence. ,我知道它没有太多意义。
I suppose you need to access it from your Controller 我想您需要从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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.