Reputation: 2824
I am having an issue running doctrine:schema:update --force because of a forgeign key constraint issue.
[Doctrine\DBAL\DBALException] An exception occurred while executing 'ALTER TABLE Product ADD CONSTRAINT FK_1CF73D312ADD6D8C FOREIGN KEY (supplier_id) REFERENCES Supplier (id) ON DELETE SET NULL':
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`wic_dev`.`#sql-5c0 a_1a12`, CONSTRAINT `FK_1CF73D312ADD6D8C` FOREIGN KEY (`supplier_id`) REFERENCES `Supplier` (`id`) ON DELETE SET NULL)
[PDOException] SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`wic_dev`.`#sql-5c0 a_1a12`, CONSTRAINT `FK_1CF73D312ADD6D8C` FOREIGN KEY (`supplier_id`) REFERENCES `Supplier` (`id`) ON DELETE SET NULL)
I have two tables that are creating this error: Products and Suppliers.
Products can have 1 supplier and suppliers can have many products.
Here is how I have my entities set up:
Product Entity:
/**
* @ORM\ManyToOne(targetEntity="WIC\SupplierBundle\Entity\Supplier", inversedBy="products", fetch="EAGER")
* @ORM\JoinColumn(name="supplier_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
* @Common\Versioned
* @Assert\NotBlank(message="Supplier Cannot Be Blank")
*/
protected $supplier;
Supplier Entity
/**
* @ORM\OneToMany(targetEntity="WIC\ProductBundle\Entity\Product", mappedBy="supplier", cascade={"all"})
*/
protected $products;
I currently have data in each table. I know some products are missing a supplier and suppliers are missing products.
What am I doing wrong and how can I fix this issue? I need to run this schema update so that my other tables will get updated as well.
Thanks so much for your help!
Upvotes: 1
Views: 3068
Reputation: 31959
In most cases, simply make sure you have a use
statement for the entity you're trying to create a relationship with.
This happens often when the 2 entities are not in the same bundle and therefore need to autoload them. For the error to disappear, simply do this:
In your product entity, don't forget:
use WIC\SupplierBundle\Entity\Supplier;
Upvotes: 0
Reputation: 2824
Here is how I fixed the issue. In my products table I was storing values as "0" if the supplier wasnt found. Because it was a manytoone and onetomany relationship between the two tables, it was having a conflict because supplier_id is never 0, 0 does not match any id in the suppliers table. I had to update the products table to set any value for 0 to NULL, this made the schema update work.
Upvotes: 5