If using Doctrine you have probably come across the error message “SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘column_id’ cannot be null” at least once. This error occurs on doctrine persist when using a entity that both has mappings for a ordinary field and an Doctrine relation field (many-to-one, one-to-many) with the same name.
Code example that often generates this kind of error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<?php namespace Entities; use Doctrine\Common\Collections\ArrayCollection; /** * Entities\Test * * @Table(name="test") * @Entity(repositoryClass="Repository\TestRepository") */ class Test { /** * @var integer $Id * * @Column(name="id", type="integer", nullable=false) * @Id * @GeneratedValue(strategy="IDENTITY") */ protected $Id; /** * @var string $mapId * * @Column(name="mapId", type="integer", nullable=false) */ protected $mapId; /** * @ManyToOne(targetEntity="Test2") * @JoinColumn(name="mapId", referencedColumnName="id") */ protected $testMap; public function setTestMap(\Entities\Test2 $testMap) { $this->testMap = $testMap; return $this; } } $entity = new Test(); $entity->mapId = 1; $em->persist($entity); $em->flush(); |
I have read on some forums on the internet that you should avoid using the following mapping together with the relation annotation
1 2 3 4 5 6 |
/** * @var string $mapId * * @Column(name="mapId", type="integer", nullable=false) */ protected $mapId; |
And only use the function “setTestMap” to define the relation between your entities
1 2 3 4 5 6 7 |
$relation = new Test2(); // this variable should be a pre existing record from Doctrine entity $entity = new Test(); $entity->setTestMap($relation); $em->persist($entity); $em->flush(); |
Personally i like to define all my field mappings like the top example, that’s because if someone should view the code i want that person to see all the fields that are existing even if that person is not to familiar with Doctrine. One more thing you get by defining all the fields is when running the command to retrieve the result in a array format you get all fields.
So when i came across this error i found that using the “setTestMap” function often solve the problem without deleting the “mapId” mapping, but some times this won’t work and you have to tweak your set function a little
1 2 3 4 5 6 |
public (\Entities\Test2 $testMap) { $this->mapId = $testMap->getId(); $this->testMap = $testMap; return $this; } |