You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony开发中创建Answer实体无法获取关联Question的question_id问题

问题原因

你报错的核心原因是在AnswerController的create方法里调用了$this->getQuestion(),这个方法是调用控制器类本身的方法,而非Answer实体的方法,你继承的AbstractController本身没有定义getQuestion()方法,所以才会报方法不存在的错误,和Answer实体定义的getQuestion()无关。
其次你的answer_create路由没有接收模板传过来的问题ID参数,根本没有拿到要关联的问题实例。


修复步骤

1. 修改控制器的create方法,适配路由参数

调整AnswerController中create方法的路由定义,接收问题ID,同时注入QuestionRepository查询对应问题实例:

/**
 * Create action.
 *
 * @param \Symfony\Component\HttpFoundation\Request $request HTTP request
 * @param \App\Repository\AnswerRepository $answerRepository Answer repository
 * @param \App\Repository\QuestionRepository $questionRepository Question repository
 * @param int $id 问题ID
 * @return \Symfony\Component\HttpFoundation\Response HTTP response
 *
 * @throws \Doctrine\ORM\ORMException
 * @throws \Doctrine\ORM\OptimisticLockException
 *
 * @Route(
 *     "/create/{id}",
 *     methods={"GET", "POST"},
 *     name="answer_create",
 * )
 */
public function create(Request $request, AnswerRepository $answerRepository, QuestionRepository $questionRepository, int $id): Response
{
    // 根据路由参数查询对应问题
    $question = $questionRepository->find($id);
    if (!$question) {
        throw $this->createNotFoundException('目标问题不存在');
    }
    
    $answer = new Answer();
    $form = $this->createForm(AnswerType::class, $answer);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        // 给回答关联对应的问题
        $answer->setQuestion($question);
        $answerRepository->save($answer);

        $this->addFlash('success', 'answer_created_successfully');

        // 建议跳回问题详情页,更符合业务逻辑,替换为你自己的问题详情路由
        return $this->redirectToRoute('question_show', ['id' => $question->getId()]);
    }

    return $this->render(
        'answer/create.html.twig',
        [
            'form' => $form->createView(),
            'question' => $question
        ]
    );
}

2. 可选:修正关联映射配置

检查你的Question实体的一对多关联属性名,你当前Answer实体的ManyToOne注解写的是inversedBy="answer",如果Question实体里存储回答集合的属性是$answers(复数),需要把Answer里的注解改成inversedBy="answers",避免Doctrine关联映射报错。

3. 表单无需修改

你当前的AnswerType已经满足需求,不需要额外加问题选择字段,关联关系直接在控制器赋值即可,避免用户手动选择问题。


内容的提问来源于stack exchange,提问作者Harizu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 01:27:00