【发布时间】:2014-07-23 04:05:22
【问题描述】:
Symfony2 的新手,有一个问题是我在使用自定义 Doctrine2 查询以查找 slug 的帖子时做错了什么。
我正在使用以下方法,但想将排序顺序更改为 DESC。
$post = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post')
->findOneBy(array(
'slug' => $slug
));
这是我的自定义查询:
public function findPostsBySlug($slug)
{
return $this->createQueryBuilder('post')
->select('post')
->where('post.slug = :slug')
->setParameter('slug', $slug)
->orderBy('post.createdAt', 'DESC')
->getQuery()
->getResult();
}
收到以下错误:
Key "title" for array with keys "0" does not exist in AcmeDemoBundle:Post:show.html.twig at line 7
我做错了什么或自定义查询中缺少什么?
树枝
{% block body %}
{{ parent() }}
<div class="container">
<h2>{{ post.title }}</h2>
<p>
<small>Post by <em>{{ post.author }}</em> on <em>{{ post.createdAt|date }}</em></small>
</p>
<p>{{ post.body }}</p>
{% for reply in post.replies %}
<hr>
<p>
<small>Reply from <em>{{ reply.author }}</em> on {{ reply.createdAt|date }}</small>
</p>
<p>{{ reply.body }}</p>
{% endfor %}
<br>
{% if is_granted('IS_AUTHENTICATED_REMEMBERED') %}
<h4>Reply</h4>
{{ form(form, { action: path('acme_demo_post_createreply', { slug: post.slug }) }) }}
{% endif %}
</div>
{% endblock %}
尝试对帖子的回复进行 DESC 排序:
我正在尝试按 DESC 顺序对我的回复进行排序。我尝试按 DESC 顺序对帖子进行排序,希望回复也会按 DESC 顺序返回,但它不起作用,它们只是按 ASC 顺序返回。
如何按 DESC 顺序对帖子的回复进行排序?
控制器:
/**
* Show a post
*
* @param string $slug
*
* @throws NotFoundHttpException
* @return array
*
* @Route("/{slug}", name="acme_demo_post_show")
* @Template("AcmeDemoBundle:Post:show.html.twig")
*/
public function showAction($slug)
{
$post = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post')
->findPostsBySlug($slug);
// Form for replies
$form = $this->createForm(new ReplyType());
return array(
'post' => $post,
'form' => $form->createView()
);
}
查询我正在使用的 slug 的帖子:
public function findPostsBySlug($slug)
{
return $this->createQueryBuilder('post')
->select('post')
->where('post.slug = :slug')
->setParameter('slug', $slug)
->orderBy('post.createdAt', 'DESC')
->getQuery()
->getSingleResult();
}
回复被映射到多对多发布:
/**
* @return Array Collection
*
* @ORM\ManyToMany(targetEntity="Reply", inversedBy="post")
* @JoinTable(name="posts_replies",
* joinColumns={@JoinColumn(name="post_id", referencedColumnName="id", nullable=true)},
* inverseJoinColumns={@JoinColumn(name="reply_id", referencedColumnName="id")}
* )
*/
protected $replies;
Twig 显示对帖子的回复:
{% for reply in post.replies %}
<hr>
<p>
<small>Reply from <em>{{ reply.author }}</em> on {{ reply.createdAt|date }}</small>
</p>
<p>{{ reply.body }}</p>
{% endfor %}
【问题讨论】:
-
我刚看到你想订购帖子,但是如果你只找一个帖子不是没有用吗?因此,第一个代码将执行与我的回答相同的操作。
标签: symfony post doctrine-orm slug