symfony2 ContextErrorException:Catchable Fatal Error:类Proxies\__ CG __\...\Entity\...的对象无法转换为字符串

ABC*_*ABC 4 php orm doctrine tostring symfony

我遇到了一些奇怪的事:

我通过app/console doctrine:generate:entity以下方式创建了三个学说实体:

  • 类别
  • 用户
  • 岗位

我建立了关系,一切都与灯具数据(app/console doctrine:fixtures:load)一致.

帖子属于单个类别(category_id),并且有一个作者(user_id).

我曾经app/console doctrine:generate:crud为我的所有实体获得CRUD操作.

当我更新帖子时,我得到了这个奇怪的错误:

ContextErrorException:Catchable Fatal Error:类Proxies__CG __...\BlogBu​​ndle\Entity\Category的对象无法转换为字符串

为了正确显示我在下面使用的下拉字段PostType():

$builder ....
  ->add('categoryId','entity', array(
     'class' => 'HotelBlogBundle:Category',
     'property'=>'name'
))
->add('userId','entity',array(
     'class'=>'UserBundle:User',
     'property'=>'username'
))
Run Code Online (Sandbox Code Playgroud)

由于我指定了property选项,因此我不需要__toString()在我的实体类中使用.

如果我创建__toString()这样的(在类别和用户实体中),错误就会消失并且有效:

public function __toString()
{
    return (string) $this->getId();
}
Run Code Online (Sandbox Code Playgroud)

我不确定我是否以正确的方式做到了.

此外,由于Category&User对象被传递给category_iduser_id字段,Doctrine(或Symfony)应该能够找出id列.我错过了什么?还有另一种方法吗?

Ani*_*nil 11

我刚刚提到了这个错误(并最终在这里),我将发布对我有用的解决方案 - 因为没有其他答案.

和OP一样,我也使用Doctrine创建了一个新表并加入.

这个错误告诉我们join object不能转换为string.我们必须__toString()在对象中提供一个方法,以便它可以转换为字符串,或者我们可以使用property键指定我们想要在Form Builder中返回哪个字段.

__toString()向对象添加方法

/**
 * (Add this method into your class)
 *
 * @return string String representation of this class
 */
public function __toString()
{
    return $this->name;
}
Run Code Online (Sandbox Code Playgroud)

或者将属性键添加到表单构建器

// where `name` equals your field name you want returned
$builder->add('category', null, ['property' => 'name'])
Run Code Online (Sandbox Code Playgroud)

我只是将__toString()方法添加到我的entity,我只有字段idname- 所以唯一的字符串表示是name.