Foreign key constraint fails when trying to add custom product attribute option
-
11-10-2020 - |
Question
I added a product attribute called size
from admin with the same settings as color
attribute. Now when i programmatically try to add an option to this attribute I get a MySQL error:
Cannot save attribute SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`eav_attribute_option_value`, CONSTRAINT `EAV_ATTR_OPT_VAL_OPT_ID_EAV_ATTR_OPT_OPT_ID` FOREIGN KEY (`option_id`) REFERENCES `eav_attribute_option` (`option_id`) ON DELETE CASCADE), query was: INSERT INTO `eav_attribute_option_value` (`option_id`, `store_id`, `value`) VALUES (?, ?, ?)
Code to add option:
/* \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory $optionFactory */
$option = $this->optionFactory->create();
$option->setLabel('120cm')->setValue('120cm')->setSortOrder(0);
/* \Magento\Eav\Api\AttributeOptionManagementInterface $optionManagement */
$this->optionManagement->add(\Magento\Catalog\Model\Product::ENTITY, 'size', $option);
When I try to add attribute option color
with the same code as above, everything works fine and option is added.
What am I doing wrong?
Solution
Found an answer after posting this question. I am going to post the answer here for future reference or anyone with the same problem.
Basically, if you set option value with $option->setValue($value)
then option_id will obtain the value from $option->getValue()
intcast. And in case of the value being '120mm'
for example, the result will be 120
. That's why it fails.
So, the solution is to not do $option->setValue($value)
The problem and answer is explained in more detail here