How to Insert Frontend Labels Conditionally in Magento 2
How to Insert Frontend Labels Conditionally in Magento 2
In this post, we'll explore how to insert records into the eav_attribute_label
table in Magento 2. Specifically, we'll insert the frontend_label
from the eav_attribute
table, but only if the attribute_id
does not already exist in eav_attribute_label
.
Problem
You want to insert a new record into the eav_attribute_label
table with three columns: attribute_id
, store_id
, and value
. The value to insert is the frontend_label
from the eav_attribute
table. This insertion should only happen if the attribute_id
does not already exist in eav_attribute_label
.
Solution
Here's how you can achieve this with a MySQL query:
INSERT INTO eav_attribute_label (attribute_id, store_id, value)
SELECT eav.attribute_id, 1 AS store_id, eav.frontend_label
FROM eav_attribute eav
WHERE NOT EXISTS (
SELECT 1 FROM eav_attribute_label eal
WHERE eal.attribute_id = eav.attribute_id
);
enhanced query
INSERT INTO eav_attribute_label (attribute_id, store_id, value)
SELECT ea.attribute_id, 1 as store_id, ea.frontend_label
FROM eav_attribute ea
WHERE ea.entity_type_id = 4
AND NOT EXISTS (
SELECT 1
FROM eav_attribute_label eal
WHERE eal.attribute_id = ea.attribute_id
AND eal.store_id = 1
);
Explanation
Let’s break down the query:
INSERT INTO eav_attribute_label (attribute_id, store_id, value)
: Specifies the table and columns where you want to insert data.SELECT eav.attribute_id, 1 AS store_id, eav.frontend_label
: Selects theattribute_id
andfrontend_label
from theeav_attribute
table. We are assigning astore_id
value of1
.WHERE NOT EXISTS
: Ensures that the insertion only happens if theattribute_id
does not already exist in theeav_attribute_label
table.SELECT 1 FROM eav_attribute_label eal WHERE eal.attribute_id = eav.attribute_id
: Checks if theattribute_id
is already present in theeav_attribute_label
table. If it is, the insert is not performed.
Customization
You can adjust the query based on your specific needs:
- Modify the
store_id
as needed for your Magento 2 store. - Ensure that the
frontend_label
fromeav_attribute
correctly maps to thevalue
column ineav_attribute_label
.
This approach helps you maintain data consistency by avoiding duplicate attribute_id
entries while inserting new frontend labels into the eav_attribute_label
table.