Reputation: 11
I'm trying to make a ManyToOne association to work in doctrine, but no luck, here's the code of my relationship :
// the entity : Product
/**
* @Id
* @ManyToOne(targetEntity="ProductsModule\Entity\Configuration", inversedBy="product")
* @JoinColumns={@JoinColumn(name="id_type", referencedColumnName="id"),
* @JoinColumn(name="id_site", referencedColumnName="id")}
*/
private $configurations;
/**
* @Id
* @ManyToOne(targetEntity="ProductsModule\Entity\Picture", inversedBy="product")
* @JoinColumn(name="id_picture", referencedColumnName="id")
*/
private $picture;
and the inverse of the association is :
// the entity : Configuration
/**
* @OneToMany(targetEntity="ProductsModule\Entity\Product", mappedBy="configurations")
*/
private $product;
// the code in the controller
$product = new Product;
$product->setConfiguration($configuration); // the configuration object is retrieved from DB
$product->setPicture($picture);
$this->em->persist($product);
try
{
$this->em->flush();
}
catch (\Exception $e)
{
var_dump($e->getMessage());die();
}
The problem is that Doctrine tries to set the first column of JoinColumn (in the example above : id_type) but it ignores the second column, which throws the following error :
An exception occurred while executing 'INSERT INTO tableX (id_picture, id_type) VALUES (?, ?)' with params [1, 1]:SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`db`.`tableX`, CONSTRAINT `fk2` FOREIGN KEY (`id_site`) REFERENCES `sites` (`id`))
the product entity in itself is an entity that was born out of a ManyToMany relationship (that's why it has two primary keys), I just changed the names of the entities to keep the code private, because I'm not allowed to share it.
thank you.
Upvotes: 1
Views: 559
Reputation: 630
It seems that you have with a foreign key related to site property try to update your schema with :
app/console doctrine:schema:update --force
If you got the same error try to drop the table or the database if this will not create any problem and make sure to export the sql file of the database and remove all foreign key , import your data then re-excute the commande : app/console doctrine:schema:update --force
Upvotes: 1