0

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?

AdrienBrault
  • 7,747
  • 4
  • 31
  • 42
Jon Cram
  • 16,609
  • 24
  • 76
  • 107

1 Answers1

6

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;
AdrienBrault
  • 7,747
  • 4
  • 31
  • 42