使用OneToMany的symfony2 createAction

时间:2016-01-01 01:03:55

标签: symfony entity one-to-many many-to-one

我有2个实体。包含2列的实体类别:id, caName。包含4列的实体服务:id, seName, sePrice, caId。服务中的列caId包含类别id

我的目标是为服务创建createAction,editAction和deleteAction。我对editAction和deleteAction没有任何问题。但是,我的createAction返回500(内部服务器错误)。

日志:

捕获致命错误:传递给AppBundle \ Entity \ Service :: SetCaId()的参数1必须是AppBundle \ Entity \ Category的实例,给定整数,在/ Applications / MAMP / htdocs / symfony_luxurysalon / src / AppBundle /中调用控制器/ ServiceController.php在第67行并定义了

类别实体:

class Category
{
  /**
   * @var int
   *
   * @ORM\Column(name="id", type="integer")
   * @ORM\Id
   * @ORM\GeneratedValue(strategy="AUTO")
   * @ORM\OneToMany(
   *   targetEntity="Service",
   *   mappedBy="caId"
   * )
   */
  private $id;

  ...

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

  /**
  * Get id
  *
  * @return Service
  */
  public function getId()
  {
     return $this->id;
  }

  ...
}

服务实体:

class Service
{
   ...

  /**
  * @var int
  *
  * @ORM\Column(name="ca_id", type="integer", length=2)
  * @ORM\ManyToOne(targetEntity="Category", inversedBy="id", cascade={"persist","remove"})
  * @ORM\JoinColumn(onDelete="CASCADE")
  */
  private $caId;

  ...

  /**
  * Set caId
  *
  * @param \AppBundle\Entity\Category $caId
  *
  * @return Service
  */
  public function setCaId(\AppBundle\Entity\Category $caId = null)
  {
      $this->caId = $caId;
      return $this;
  }

  /**
  * Get caId
  *
  * @return \AppBundle\Entity\Category
  */
  public function getCaId()
  {
    return $this->caId;
  }
}

控制器:

$entity = new Service();
$entity
  ->setSeName("test")
  ->setSePrice("200");
  ->setCaId("2");

$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();

1 个答案:

答案 0 :(得分:1)

你必须将Category实例而不是id传递给setCaId()方法(顺便说一句。如果你不希望传递id,这个名称会产生误导,例如{{1}会更合适)。因此,您必须首先从存储库中查找id为2的类别,然后将此类别传递给方法:

setCategory()

您可能希望添加一些处理$doctrine = $this->getDoctrine(); $category = $doctrine->getRepository('AppBundle:Category')->find(2); $service = new Service(); $service->setCaId($category); $em = $doctrine->getManager(); $em->persist($service); $em->flush(); 未返回结果的情况的逻辑(例如,当没有id为2的类别时)。