I am quite new to Doctrine and need help in one situation. I have 2 simple tables Albums & Genre. Please check the structures below:
Albums
id | title | genre_id | createdon
1 | Album 1 | 1 | 21/05/2015
2 | Album 2 | 2 | 21/05/2015
Genre
id | genre | active
1 | Pop | 1
2 | Blue | 1
3 | Rock | 1
4 | Country | 1
genre_id from Albums table is mapped to id column of Genre table.
In Albums entity I have mapped this by the below process:
/**
* @ORM\OneToOne(targetEntity="Genre", mappedBy="albums")
* @ORM\JoinColumn(name="genre_id", referencedColumnName="id")
**/
private $genre;
public function getGenre(){
return $this->genre;
}
public function setGenre($value)
{
$this->genre = $value;
return $this;
}
I can fetch genre name flawlessly by getGenre() method but the problem is while inserting value into the database. I need to insert genre_id which is an integer value but after calling setGenre() method from controller I am getting the following error:
Expected value of type "Album\Entity\Genre" for association field "Album\Entity\Albums#$genre", got "string" instead.
I have also tried by specifying another private variable like the original column name i.e genre_id like below:
/** @ORM\Column(type="integer") */
protected $genre_id;
public function setGenre($value)
{
$this->genre_id = $value;
return $this;
}
But then I am getting the following error:
An exception occurred while executing 'INSERT INTO Albums (title, createdon, genre_id) VALUES (?, ?, ?)' with params ["nfhgfh", "21/05/2015", null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'genre_id' cannot be null
I am calling the entity from controller like this:
$albums = new Albums();
$albums->setTitle($postData['title']);
$albums->setGenre($postData['genre_id']);
$albums->setCreatedon(date('d/m/Y'));
$this->em()->persist($albums);
$this->em()->flush();
I am badly stuck in this problem and need your help. I am not having any clue how its getting a null value instead. Please help.