Symfony3一对多关系__toString错误

时间:2017-11-12 20:13:37

标签: symfony doctrine associations entities

我正在关注symfony documentation for associations,我创建了产品和类别实体。

在我的产品实体中,我有:

/**
 * @ORM\ManyToOne(targetEntity="Category", inversedBy="products")
 * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
 */
private $category;

在我的分类实体中,我有:

/**
 * @ORM\OneToMany(targetEntity="Product", mappedBy="category")
 */
private $products;

以下是生成的表的外观:

mysql> show create table product \G
*************************** 1. row ***************************
       Table: product
Create Table: CREATE TABLE `product` (
  `id` bigint(20) unsigned NOT NULL,
  `category_id` int(10) unsigned DEFAULT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `details` text COLLATE utf8_unicode_ci COMMENT '(DC2Type:json_array)',
  PRIMARY KEY (`id`),
  KEY `IDX_D34A04AD12469DE2` (`category_id`),
  CONSTRAINT `FK_D34A04AD12469DE2` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
1 row in set (0.00 sec)

mysql> show create table category \G
*************************** 1. row ***************************
       Table: category
Create Table: CREATE TABLE `category` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `parent_id` int(10) unsigned DEFAULT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
1 row in set (0.00 sec)

mysql>

我还安装了EasyAdmin软件包。现在,我转到EasyAdmin并打开“类别”表并插入一行。然后我转到“产品”表,当我点击“添加产品”按钮时,我收到错误:

Catchable Fatal Error: Object of class AppBundle\Entity\Category could not be converted to string

可以通过添加一个魔术方法__toString来解决问题,该方法将$ this-> name返回到Category实体。

问题:

1-我做错了什么?为什么我需要将__toString方法添加到Category实体?

2-如果这是正常的,为什么在symfony手册中没有提到这个?

2 个答案:

答案 0 :(得分:1)

毫无疑问这是正常行为。我已经使用EasyAdminbundle多次完成了这项工作。

您必须实施__toString()方法。

  

显示表示与其他实体的关联的字段   作为清单。因此,您必须定义__toString()   在Doctrine关系中使用的任何实体中的PHP方法。   否则,您将看到错误消息,因为后端不能   将相关对象表示为字符串。

这是在这里的文档:https://symfony.com/doc/current/bundles/EasyAdminBundle/book/edit-new-configuration.html

答案 1 :(得分:0)

两件事:

1)在关系的“多”侧向实体添加__toString()方法,该方法返回标识实体的字符串。

2)确保__toString()方法在每种情况下都返回一个字符串,即使实体是完全空的。通常,您必须初始化__toString()作为空字符串返回的属性。

示例:

private $name = ''; // initialize $name as an empty string

public function __toString()
{
    return $this->name; // which is a string in any circumstance
}