Symfony 如何传入 url 多对多关系的第一个值?

Symfony How to pass in url the first value of a ManytoMany relation?

在我的树枝中,我想在 url 中传递我的类别名称以查看该类别的详细信息。

在我的控制器中,我将其作为路由:

     **
     * @Route("/{name}", name="category_name", methods={"GET"})
     */
    public function categorie(CategoryRepository $categoryRepository): Response
    {
        return $this->render('category/index.html.twig', [
            'categories' => $categoryRepository->findAll(),
        ]);
    }

之后,我将其放入我的树枝中以获取名称的第一个值:

{% for test in tests %}
    {% set array = test.categories|join(' - ')|split(' ', 2) %}
        <div class="category"><a href="{{ path('category_name', {'name': attribute(array, 0)}) }}">{{ attribute(array, 0) }}</a></div>
{% endfor %}

我的测试class:

<?php

namespace App\Entity;

use App\Repository\TestRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=TestRepository::class)
 */
class Test
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $title;

    /**
     * @ORM\Column(type="text")
     */
    private $content;

    /**
     * @ORM\ManyToMany(targetEntity=Category::class, inversedBy="test_category")
     */
    private $categories;
}

我的分类class:

<?php

namespace App\Entity;

use App\Repository\CategoryRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=CategoryRepository::class)
 */
class Category
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\ManyToMany(targetEntity=Test::class, mappedBy="categories")
     */
    private $test_category;
}

但是我有这个错误信息:

An exception has been thrown during the rendering of a template ("Parameter "name" for route "category_name" must match "[^/]++" ("" given) to generate a corresponding URL.").

我猜您检索第一个类别名称的方式不是特别安全。试试这个:

{% for test in tests %}
    {% set category_name = (test.categories | first).name | default %}
    {% if category_name %}
        <div class="category">
            <a href="{{ path('category_name', {'name': category_name}) }}">
                {{ category_name }}
            </a>
        </div>
    {% endif %}
{% endfor %}

使用 default 过滤器和额外的 if 我们可以避免 twig 在没有可用类别时尝试输出链接。

附带说明一下,您将 运行 遇到类别名称不 URL 安全的问题,除非您建立检查和保护措施。

最简单的方法是使用 sluggable doctrine 扩展,这样您就可以得到类别名称的 URL 安全表达式。

详情请看这里: