gpt4 book ai didi

Symfony - 如何以 "many-to-one"形式保存外键

转载 作者:行者123 更新时间:2023-12-02 19:00:40 24 4
gpt4 key购买 nike

我是 Symfony 2 的新手,我正在尝试为具有外键的内容类型构建一个表单。我不知道如何使用表单保存外键。

我的两个表是“类别”和“问题”。一个问题属于一个类别(多对一)。所以我在实体中的 Question.php 文件包含:

<?php

namespace Iel\CategorieBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* Question
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Iel\CategorieBundle\Entity\QuestionRepository")
*/
class Question
{
/**
* @ORM\ManyToOne(targetEntity="Iel\CategorieBundle\Entity\Categorie")
* @ORM\JoinColumn(nullable=false)
*/
private $categorie;
/**
* Set categorie
*
@param Iel\CategorieBundle\Entity\Categorie $categorie
*/
public function setCategorie(\Iel\CategorieBundle\Entity\Categorie $categorie)
{
$this->categorie = $categorie;
}
/**
* Get categorie
*
@return Iel\CategorieBundle\Entity\Categorie
*/
public function getCategorie()
{
return $this->categorie;
}

我尝试过像这样构建 Controller 函数,但这不是正确的语法:

public function addquestionAction()
{
$question = new Question;

$form = $this->createFormBuilder($question)
->add('titre', 'text')
->add('auteur', 'text')
->add('contenu', 'textarea')
->add('category_id', $this->getCategorie())
->getForm();

$request = $this->get('request');

我不知道如何使用此表单在问题表中写入当前的category_id。

最佳答案

更好的方法是声明“实体”类型的“类别”。像这样的事情:

$form = $this->createFormBuilder($question)
->add('titre', 'text')
->add('auteur', 'text')
->add('contenu', 'textarea')
->add('category', 'entity', array(
'class' => 'IelCategorieBundle:Categorie',
'property' => 'name',
))
->getForm();

这应该创建一个选择,其中选项值是类别 ID,选项显示值是类别名称。保留 $question 对象会将类别 ID 插入到“questions”表的外键字段中。

关于Symfony - 如何以 "many-to-one"形式保存外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19710595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com