【问题标题】:Object of class Doctrine\ORM\PersistentCollection could not be converted to string类 Doctrine\ORM\PersistentCollection 的对象无法转换为字符串
【发布时间】:2014-01-26 15:05:36
【问题描述】:

我用 Symfony2 制作了一个 Web 应用程序,其中一个 User 与实体 Mission 有一个数组关联 ManytoMany。用户可以通过表单上传实体$product,表单传递的数据之一就是与用户关联的任务。

当我尝试上传数据时,出现错误:

ContextErrorException: Catchable Fatal Error: Object of class   
Doctrine\ORM\PersistentCollection could not be converted to string in     
C:\BitNami\wampstack-5.4.23- 
0\frameworks\symfony\vendor\doctrine\dbal\lib\Doctrine\DBAL\Statement.php line 103

很明显,Doctrine 不知道如何保存任务的价值。

我该如何管理它?

我也不知道如何在我的产品实体中声明任务对象。现在简直就是这样:

/**
 * @var string
 *
 * @ORM\Column(name="mission", type="string", length=255)
 */
protected $mission;

更新---

我的控制器现在是:

       $form = $this->createFormBuilder($product)
           ->add('name', 'text')
           ->add('mission', 'entity', array('required' => true, 'multiple' => false, 'class' => 'AcmeManagementBundle:Mission', 'query_builder' => function($repository) { return $repository->createQueryBuilder('c')->orderBy('c.id', 'ASC'); },))              
      //...
           ->add('save', 'submit')
           ->getForm(); 

更新---

现在可以了,但我有一个问题。当出现上传 $product 对象的表单时,还会出现 ->add('mission', 'entity'... 在此字段中,我可以看到存储的所有任务,而不仅仅是与用户关联的任务。如何我应该更换控制器吗? 我试着像这样改变我的控制器:

       $product = new Product();
       $product->setMission($this->getUser()->getMission());

【问题讨论】:

  • 在你的实体类中插入public function __toString() { return $this->mission; }
  • 对不起,我真的是 Symfony 和 php 的新手。我必须将它添加到我的 product.php 实体中吗?
  • 是的,在您的 Product.php 实体中:)
  • 但问题依然存在? 我尝试了一些方法,但我没有成功!
  • 但是您必须在设置任务的控制器中使用 foreach。

标签: php symfony doctrine arraycollection


【解决方案1】:

用于管理用户和任务之间的多对多关系

在 User.php 中:

/**
 * @var \Doctrine\Common\Collections\ArrayCollection
 * 
 * @ORM\ManyToMany(targetEntity="Your\SuperBundle\Entity\Mission", inversedBy="users", orphanRemoval=true)
 * @ORM\JoinTable(name="user_mission")
 */
private $missions;

在 Mission.php 中:

/**
 * @var \Doctrine\Common\Collections\ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity="Your\SuperBundle\Entity\User", mappedBy="missions", cascade={"all"}, orphanRemoval=true)
 */
private $users;

然后为您的表单:

http://symfony.com/doc/current/reference/forms/types/collection.html 用于在您的用户表单中管理任务集合。

看看“type”和“allow_add”

【讨论】:

  • 现在可以了,但我有一个问题。当出现上传 $product 对象的表单时,还会出现 ->add('mission', 'entity'... 在此字段中,我可以看到存储的所有任务,而不仅仅是与用户关联的任务。如何我应该更换控制器吗?我尝试使用 ->add('mission','collection' .. 但出现错误。
  • 你想创建一个新任务,还是选择一个已经创建的?
  • 我也有类似的问题here,是否符合您的问题?如果可以的话,谢谢你的帮助。
猜你喜欢
  • 2016-01-11
  • 2014-12-31
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多