【问题标题】:Symfony3 :: Handle ManyToMany relationsSymfony3 :: 处理多对多关系
【发布时间】:2016-12-02 16:12:08
【问题描述】:

我正在尝试保存用户和类别之间的多对多关系。实际上,我正在尝试使用给定的用户保存我的类别,但这不起作用。

表格

$builder->add('name')
        ->add('users', EntityType::class, array(
            'label' => 'Benutzer',
            'class' => 'AppBundle\Entity\User',
            'multiple' => true,
            'expanded' => true,
            'required' => false,
            'choice_label' => function (User $user) {
                return $user->getUsername();
            }
        ))
        ->add('submit', SubmitType::class, array(
            'label' => 'Speichern'
        ));

表单处理程序

public function onSuccess(Request $request)
{
    // Get category from form
    $category = $this->getForm()->getData();

    // Redirect to parent category when setted
    if ($this->parent) {
        $category->setParent($this->parent);
        $response = new RedirectResponse($this->router->generate('categories.view', [
            'category' => $this->parent->getId()
        ]));
    } else {
        // Build new redirect response
        $response = new RedirectResponse($this->router->generate('categories.view', [
            'category' => $category->getId()
        ]));
    }

    try {
        // Save category in database
        $this->em->merge($category);
        $this->em->flush();
    } catch (ORMException $ex) {
        throw $ex;
    }

    return $response;
}

【问题讨论】:

  • 什么不起作用?您还没有显示所有代码!
  • @AlvinBunk 我确实编辑了我的帖子

标签: symfony


【解决方案1】:

也许您必须先反序列化实体 $category?

$detachedCategory = unserialize($category); 
$this->em->merge($detachedCategory);
$this->em->flush();

我发现了这个链接: How to manage deserialized entities with entity manager?

不确定这是否是答案,但您可能需要进行更多研究。

【讨论】:

  • 感谢您的快速答复。这没有帮助,我的 $category 变量没有序列化:“警告:unserialize() 期望参数 1 是字符串,给定对象”
  • 如果您改用$this->em->persist($category); 会怎样?还是必须使用合并?
  • unserialize 确实会抛出此异常,因为我的 $category 变量是实体的实例,而不是序列化字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多