php - Doctrine sets valid parameters to null on flush()

294

I have two many-to-one relationships, where objects$countryFrom and$countryTo fromNotification get the values from columnid_country_form andid_country_to and looks inCountry table for anid with the same value. I have setters and getters for all the properties.

Entity Notification

class Notification
{
/**
 * @ORM\ManyToOne(targetEntity="Country")
 * @ORM\JoinColumn(name="id_country_from", referencedColumnName="id")
 */
private $countryFrom;

/**
 * @ORM\ManyToOne(targetEntity="Country")
 * @ORM\JoinColumn(name="id_country_to", referencedColumnName="id")
 */
private $countryTo;

/**
 * @var integer
 *
 * @ORM\Column(name="id_country_from", type="integer", nullable=false)
 */
private $idCountryFrom;

/**
 * @var integer
 *
 * @ORM\Column(name="id_country_to", type="integer", nullable=false)
 */
private $idCountryTo;   
}


Entity Country

class Country
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $id;  
}

However, when I want to insert data in DB from the controller, the properties associated withid_country_form andid_country_toare setted to null.


Controller Method

$notif = new Notification;
$notif->setCountryFrom(5); // SET to NULL 
$notif->setCountryTo(6); // SET to NULL       
$notif->setCreatedAt(new \DateTime());

$em->persist($notif);
$em->flush();


var_dump($notification) after persist()

object(AppBundle\Entity\Notification)[457]
private 'countryFrom' => null
private 'countryTo' => null
private 'idCountryFrom' => int 5 // SET
private 'idCountryTo' => int 6   // SET    
private 'createdAt' => 
  object(DateTime)[448]
     public 'date' => string '2016-06-14 06:32:35.000000' (length=26)
     public 'timezone_type' => int 3
     public 'timezone' => string 'UTC' (length=3)
private 'id' => null

Here we see that idCurrencyFrom and idCurrencyTo are setted after persist(), but the next error occurs:

An exception occurred while executing 'INSERT INTO alerts (id_currency_from, id_currency_to, active, created_at) VALUES (?, ?, ?, ?)' with params [null, null, "2016-06-14 06:32:35"]:

The code worked before I set the many-to-one relationships.

298

Answer

Solution:

I can't assume without looking your setter methods but you should pass entity to setter method not id. For example;

 $country = $em->getRepository('AppBundle:Country')->find(5);
 $notif->setCountry($country);   

People are also looking for solutions to the problem: How to solve php can not run?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.