如何查询具有ID并且路线中还有slug的特定帖子?这是为了更新特定的帖子。我已经尝试将slug添加到更新路径中无济于事(未找到异常触发器),找到具有id和slug值的帖子的正确方法是什么?
路线:
显示
BloggerBlogBundle_blog_show:
path: /{id}/{slug}
defaults: { _controller: BloggerBlogBundle:Blog:show }
requirements:
methods: GET
id: \d+
更新
BloggerBlogBundle_blog_update:
path: /{id}/{slug}/update
defaults: { _controller: BloggerBlogBundle:Blog:update, id: $id }
requirements:
id: \d+
控制器:
BlogController(更新动作)
public function updateAction($id, Request $request)
{
$em = $this->getDoctrine()
->getManager();
$blog = $em->getRepository('BloggerBlogBundle:Blog')
->find($id);
if (!$blog) {
throw $this->createNotFoundException(
'No blog was found for this id' . $id
);
}
$form = $this->createFormBuilder($blog)
->add('title', 'text')
->add('author', 'text')
->add('blog', 'text')
->add('image', 'text')
->add('tags', 'text')
->add('save', 'submit')
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$em->flush();
// return new Response('Blog was updated successfully');
return $this->redirect($this->generateUrl('BloggerBlogBundle_homepage'));
}
$build['form'] = $form->createView();
return $this->render('BloggerBlogBundle:Blog:create.html.twig', $build);
}
答案 0 :(得分:2)
好的,弄清楚我做错了什么。需要将$ slug传递给updateAction参数并使用每个nifr的findOneBy(数组)(感谢您的帮助)。
更新路线:
BloggerBlogBundle_blog_update:
path: /{id}/{slug}/update
defaults: { _controller: BloggerBlogBundle:Blog:update }
requirements:
id: \d+
更新了控制器:
public function updateAction($id, $slug, Request $request)
{
$em = $this->getDoctrine()
->getManager();
$blog = $em->getRepository('BloggerBlogBundle:Blog')
->findOneBy(array(
'id' => $id,
'slug' => $slug
));
if (!$blog) {
throw $this->createNotFoundException(
'No blog was found for this id/slug: ' . $id. $slug
);
}
$form = $this->createFormBuilder($blog)
->add('title', 'text')
->add('author', 'text')
->add('blog', 'text')
->add('image', 'text')
->add('tags', 'text')
->add('save', 'submit')
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$em->flush();
// return new Response('Blog was updated successfully');
return $this->redirect($this->generateUrl('BloggerBlogBundle_homepage'));
}
$build['form'] = $form->createView();
return $this->render('BloggerBlogBundle:Blog:create.html.twig', $build);
}
答案 1 :(得分:0)
您可以使用doctrine的id
方法同时查询与slug
和findOneBy(array $criteria)
匹配的条目。
$request = $this->getRequest()->request;
$em = $this->getDoctrine()->getManager();
$repository = $em->getRepository('AcmeYourBundle:Entity'):
$entity = $repository->findOneBy(array(
'id' => $request->get('id'),
'slug' => $request->get('slug'),
));
文档章节Working with objects # By simple conditions涵盖了此主题。