Symfony/Doctrine: “Catchable Fatal Error: Object of class <type> could not be converted to string” when persisting

做~自己de王妃 提交于 2019-12-08 10:42:45

问题


A symfony2 application has a Job entity that has as a property of type WebSite.

A simplified representation of this without other properties or methods:

/**
 * @ORM\Entity
 * @ORM\Table(name="Job")
 */
class Job
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;


    /**
     * @ORM\Column(type="integer", name="website_id", nullable=false)
     * @ORM\ManyToOne(targetEntity="Example\ExampleBundle\Entity\WebSite")
     */
    protected $website;
}

Symfony/Doctrine is trying to cast the website property to a string when persisting resulting in the error:

Catchable Fatal Error: Object of class Example\ExampleBundle\Entity\WebSite could not be converted to string in /vendor/doctrine/dbal/lib/Doctrine/DBAL/Statement.php line 131

I believe the above @ORM\Column annotation denotes the website property to be an integer. I don't understand why Symfony/Doctrine wishes to try and convert the website property to a string.

Non-ideal workarounds I have tried in an attempt to resolve the matter:

  • Adding __toString() method to WebSite, returning a string representation of the id property, causes the correct value to ultimately end up in the Job.website_id datafield; this workaround is impractical as I will in the future need __toString() to be available to present a string elsewhere in the application.

  • Removing the @ORM\Column annotation from the website property; this results in all future diff-generated migrations (php app/console doctrine:migrations:diff) removing the 'not null' aspect of the relevant database field.

Are there any changes I should make to the above annotation to inform Symfony/Doctrine to call the getId() method of WebSite to get what it needs when persisting? Are there any changes I could make to WebSite to achieve the same?

What changes are required to ensure that the above annotation can remain in place such that Doctrine ultimately calls WebSite.getId() to get what it needs when persisting instead of trying to cast the object to a string?


回答1:


You have to remove the @ORM\Column(type="integer" annotation from the $website property.

To be sure that the website_id column keeps the NOT NULL constraint, add a JoinColumn annotation with nullable=false in it:

/**
 * @var Example\ExampleBundle\Entity\WebSite
 * 
 * @ORM\ManyToOne(targetEntity="Example\ExampleBundle\Entity\WebSite")
 * @ORM\JoinColumn(name="website_id", referencedColumnName="id", nullable=false)
 */
protected $website;


来源:https://stackoverflow.com/questions/11512262/symfony-doctrine-catchable-fatal-error-object-of-class-type-could-not-be-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!