如何通过帖子访问评论存储库



我在帖子和评论实体之间OneToMany关系。

现在,我可以使用$post->getComments()轻松访问帖子的评论。

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

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

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

是否可以访问此方法?

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

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

use AppBundleEntityComment;
public function listComments()
{
$comments = $this->getDoctrine()
->getRepository(Comment::class)
->findAllOrdered();
}
class PostRepository extends EntityRepository
{
private $em;
public function __construct(EntityManagerInterface $em, MappingClassMetadata $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();

最新更新