【问题标题】:Saving ManyToOne-Relationships with Symfony an FOSRestBundle使用 Symfony 和 FOSRestBundle 保存多对一关系
【发布时间】:2015-08-26 16:41:23
【问题描述】:

我在我的项目中使用 symfony 和 FOSRestBundle。我用我的代码制作了这个例子以降低复杂性。可能忘记重命名变量了。

我在保存具有 ONE 类别的文章时遇到问题。这些类别已经存在于数据库中。我不想创建新类别

我不确定完成这项工作的最佳做​​法是什么。所以我尝试了几种方法并记录了错误消息(请参阅表单类型)

实体

class Article
{
  private $id;
  private $name;
  /* this is ManyToOne */
  private $category;

  function getId() {/* ... */}
  function setName($name) {/* ... */}
  function getName() {/* ... */}
  function setCategory(Category $cat) {/* ... */}
  function getCategory() {/* ... */}
}

class Category
{
  private $id;
  private $name;

  function getId() {/* ... */}
  function setName($name) {/* ... */}
  function getName() {/* ... */}
}

JSON POST

{
  "name": "testName"
  "category": {
    "name": "nameOfAExistingCategory"
  }
}

表单类型

class ArticleType extends AbstractType
{
  /**
   * @param FormBuilderInterface $builder
   * @param array $options
   */
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
      $builder
          ->add('name')

          // here i tried out several ways of saving the category
          ->add('category')
          // error-message
          //Argument 1 passed to AppBundle\\Entity\\Article::setCategory() must be an instance of AppBundle\\Entity\\Category, array given, called in \...../vendor\/symfony\/symfony\/src\/Symfony\/Component\/PropertyAccess\/PropertyAccessor.php on line 410 and defined",

          // OR
          ->add('category', new CategoryType())
          // error-message
          // A new entity was found through the relationship 'AppBundle\\Entity\\Article#category' that was not configured to cascade persist operations for entity: AppBundle\\Entity\\Category@000000000c958844000000003bf8ec58. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist  this association in the mapping for example @ManyToOne(..,cascade={\"persist\"}). If you cannot find out which entity causes the problem implement 'AppBundle\\Entity\\Category#__toString()' to get a clue


          // OR
          ->add('category', 'entity', array(
              'class' => 'AppBundle:Category',
          ))
          // error-message
          // message":"category:\n                    ERROR: This value is not valid
      ;
  }

  /* ... */
}

控制器

public function postAction(Request $request) {
  $form = $this->createForm(
      new ArticleType(),
      new Article(),
      array('method' => 'POST'));

  $form->submit($request->request->all());

  if (!$form->isValid()) {
      throw new HttpException(Codes::HTTP_BAD_REQUEST, $form->getErrors(true, false));
  }

  $em = $this->getDoctrine()->getManager();

  $article = $form->getData();
  $em->persist($article);
  $em->flush();

  return $article;
}

【问题讨论】:

    标签: php symfony doctrine fosrestbundle


    【解决方案1】:

    下面是工作示例:

    实体

    class Article
    {
      ...
      private $category;
    
      ...
      function setCategory(Category $cat) {/* ... */}
      function getCategory() {/* ... */}
    }
    
    class Category
    {
      private $id;
    
      ...
    
      function getId() {/* ... */}
    }
    

    JSON POST

    {
      "name": "testName",
      "category": 1
    }
    

    表单类型

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
      $builder
          ->add('name')
          ->add('category', 'entity', [
            'class' => CATEGORY_CLASS,
            'property' => 'id'
          ])
      ;
    }
    

    控制器

    public function postAction(Request $request) {
      $article = new Article();
      $form = $this->createForm(
          new ArticleType(),
          $article,
          array('method' => 'POST'));
    
      $form->handleRequest($request);
    
      if (!$form->isValid()) {
          throw new HttpException(Codes::HTTP_BAD_REQUEST, $form->getErrors(true, false));
      }
    
      if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($article);
        $em->flush();
    
        return $article; 
      }
    
      return $form;
    }
    

    【讨论】:

    • CATEGORY_CLASS 是类别实体的完全限定类名,给定 >=php5.5 可以替换为 Category::class
    • @k0pernikus 感谢您提供的信息。在我的示例中,CATEGORY_CLASS 只是一个伪代码,它可以保存诸如AcmeDemoBundle:Category、或Acme\DemoBundle\Entity\CategoryCategory::class 之类的值( >=.php v5.5)
    • 酷!这似乎有效。问题是前端(AngularJS)生成的json就像你在我的问题中看到的那样。有没有办法像现在这样使用它?
    猜你喜欢
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 2015-03-05
    相关资源
    最近更新 更多