首页 > 解决方案 > “在将此参数添加到参数时,无法猜测如何从参数“person_id”的请求信息中获取 Doctrine 实例

问题描述

我有一个来自 symfony 4 的错误“无法猜测如何从参数“person_id”的请求信息中获取 Doctrine 实例,已经尝试了我在 stackoverflow 上找到的相关问题的选项,但他们都建议用 @paramconverter 解决这个问题,但是这种方法与@route有关,我认为这不是我需要的。

这是控制器中的代码:

/**
 * @Route("/skill/new/", name="new_skill")
 * Method({"GET", "POST"})
 * @param Request $request
 * @param Person $person_id
 * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
 */
public function new(Request $request, Person $person_id) {
    $skill = new Skill();
    $form = $this->createFormBuilder($skill)
        ->add('name', TextType::class, array('attr' => array('class' => 'form-control')))
        ->add('level', TextareaType::class, array(
            'attr' => array('class' => 'form-control')
        ))
        ->add('save', SubmitType::class, array(
            'label' => 'Create',
            'attr' => array('class' => 'btn btn-primary mt-3')
        ))
        ->getForm();
    $form->handleRequest($request);
    if($form->isSubmitted() && $form->isValid()) {
        $skill = $form->getData();
        $entityManager = $this->getDoctrine()->getManager();
        $person = $entityManager->getRepository(Person::class)->find($person_id);
        $person->addSkill($skill);
        $entityManager->persist($skill);
        $entityManager->persist($person);
        $entityManager->flush();
        return $this->redirectToRoute('skill_list');
    }
    return $this->render('main/new.html.twig', array(
        'form' => $form->createView()
    ));
}

并来自 Person 实体

class Person
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

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

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Skill", mappedBy="person")
 */
private $skills;

public function __construct()
{
    $this->skills = new ArrayCollection();
}

public function getId(): ?int
{
    return $this->id;
}

public function getName(): ?string
{
    return $this->name;
}

public function setName(string $name): self
{
    $this->name = $name;

    return $this;
}

/**
 * @return Collection|Skill[]
 */
public function getSkills(): Collection
{
    return $this->skills;
}

public function addSkill(Skill $skill): self
{
    if (!$this->skills->contains($skill)) {
        $this->skills[] = $skill;
        $skill->setPerson($this);
    }

    return $this;
}

public function removeSkill(Skill $skill): self
{
    if ($this->skills->contains($skill)) {
        $this->skills->removeElement($skill);
        // set the owning side to null (unless already changed)
        if ($skill->getPerson() === $this) {
            $skill->setPerson(null);
        }
    }

    return $this;
}

}

使用@paramconverter,我在“* @Route(”/skill/new/{id}", name="new_skill" 之类的路由中写了 id param,但他给出了另一个错误“没有为“GET /skill/new”找到路由”

我想要实现的是,当我创建新技能时,它会绑定到具有特定 ID 的特定人,所以我进行了 ManyToOne 关联。因此,当我在路线“/person/{{ person.id }}”上时,我需要为这个特定的 id 添加技能,而不是每个人。

我想我在函数参数上写 person_id 时犯了一个错误,但否则它无法在 entitymanager 中找到这个参数。我该如何解决这个问题?

标签: phpsymfonydoctrine-orm

解决方案


问题出在 Route 定义和方法签名中。Symfony 无法推断Person $person_id它应该获取哪个。如果您希望这是一个实体,您应该为 id 分配一个 url 参数,例如

@Route("/skill/new/{person_id}", name="new_skill")

这会将 URL 从http://example.com/skill/new更改为http://example.com/skill/new/123123要为其获取Person-object 的 id。现在你必须在你的 URL 中有一个人 ID,否则路由将不匹配(正如你已经注意到的)。您可以通过更改方法签名使其成为可选:

/**
 * @Route("/skill/new/{person_id}", name="new_skill")
 * Method({"GET", "POST"})
 * @param Request $request
 * @param Person $person_id
 * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
 */
public function new(Request $request, Person $person_id = null) {

通过允许$person_idurl 参数为 null 应该是可选的,因此您应该能够使用http://example.com/skill/skill/newhttp://example.com/skill/skill/new/123

如果您不想要实体并且只想要一种方法来选择性地从 URL 中获取它而不显式指定路由参数,您可以稍微更改代码:

/**
 * @Route("/skill/new", name="new_skill")
 * Method({"GET", "POST"})
 * @param Request $request
 * @param Person $person_id
 * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
 */
public function new(Request $request) {
    $person_id = $request->query->get('person_id');
    ...

如果您现在使用现有 URL 并添加一个 URL 参数,它将在您的操作中读取,例如http://example.com/skill/new?person_id=1234将设置$person_id为 1234。当您不指定参数时将为空。

Symfony 还具有调试命令,可帮助您检查存在哪些路由以及它们是否匹配:

bin/console debug:router

bin/console router:match /skill/new

推荐阅读