Symfony 5 - 在类别 url 中显示 id 和 slug,并在 slug 更新时通过 id 找到它

标签 symfony routes seo

我的类别 url 包含 id 和 slug,如 https://myapp.com/category/56-category-name (id field = 56 and slug field = category-name in the DB),当更新类别名称时,DB中的slug字段被更新但id仍然相同。
我想显示我的类别,只要 id 是正确的,当然显示正确的 url。在这种情况下,我认为 SEO 仍然是正确的。
这是我的展示方法:

/**
 * @Route("/category/{id}-{slug}", name="category_show", requirements={"id"="\d+"})
 */
public function show(CategoryRepository $categoryRepository, $slug, $id): Response
{

    $category = $categoryRepository->find($id);
    if($category->getSlug() !== $slug) {
        return $this->redirectToRoute('category_show', [
            'id' => $id,
            'slug' => $category->getSlug()
        ]);
    }
    return $this->render('category/show.html.twig', [
        'category' => $category
    ]);
}
如果给定的 id 存在于数据库中,它就可以工作,否则我会收到错误 在 null 上调用成员函数 getSlug() .我可以抛出 NotFoundException,但我认为这种方法使用了多次查询。
所以请帮助我以更大的灵活性和性能正确地做这些。
如果我想在帖子 url 中显示类别以及 https://myapp.com/56-category-name/23-post-title怎么办??
提前致谢

最佳答案

使用 findOneBy()并检查结果是否为 null

/**
 * @Route("/category/{id}-{slug}", name="category_show", requirements={"id"="\d+"})
 * @Route("/{id}-{slug}/{idArticle}-{postSlug}", name="article_show", requirements={"idArticle"="\d+"})
 */
public function show(CategoryRepository $categoryRepository, $slug, $id, $idArticle = false, $postSlug = false ): Response
{

    $category = $categoryRepository->findOneBy(['id'=>$id]);
    if(is_null($category)){
      throw new NotFoundHttpException(); //404, nothing found
    }else{
      //Category found.
      if($idArticle){ //  https://myapp.com/56-category-name/23-post-title
         //Article route, put your logic here 
      }else{ //https://myapp.com/category/56-category-name 
        // Category route, logic here
        if($category->getSlug() !== $slug) {
           return $this->redirectToRoute('category_show', [
              'id' => $id,
              'slug' => $category->getSlug()
           ]);
        }
        return $this->render('category/show.html.twig', [
          'category' => $category
        ]);
      }
    }
}

关于Symfony 5 - 在类别 url 中显示 id 和 slug,并在 slug 更新时通过 id 找到它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65919363/

相关文章:

c# - 使用 RedirectToAction 将信息传递给另一个操作 - MVC

php - 一次运行多个Symfony命令

ruby-on-rails - Rails 3 带有斜线和嵌套资源的路线

symfony - 预过滤列表的 Sonata 管理员操作按钮

asp.net-mvc-2 - ASP.NET MVC2 和路由

codeigniter - 在 Codeigniter 中创建一个 SEO 友好的 url

HTTP、HTTPS、共享 SSL 和 SEO

node.js - 搜索引擎索引 - SEO 的 PhantomJs 快照的任何替代方案?

postgresql - 学说迁移包和 postgres 架构 : diff does not work properly

php - Twig `constant()` 作为数组键