Being a developer, you need to take care of many things and at the same time, you have to fulfill the client’s requirements efficiently. Many a time, it happens that you have to capture unique values from your client and store them in a database for later use. And, if you master the database to handle data using PHP queries then things will be a lot easier for you to work and fulfill Magento requirements.
You probably came across a requirement of storing it in one column without repetition or storing similar items for which you need to create one unique key for that column. Doing this will help you from storing similar data in the same database table column. So, if you are looking for creating a unique key column in the db_schema.xml file of Magento 2, here is how you can do it.
How to Create a Unique key Column in db_schema.xml file of Magento 2?
Move to the below path
app\code\Vendor\Extension\etc\db_schema.xml
And add the code as given below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0"?> <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="persons" resource="default" engine="innodb" comment="Persons"> <column xsi:type="int" name="id" padding="10" unsigned="true" nullable="false" identity="true" comment="Id"/> <column xsi:type="varchar" name="last_name" nullable="false" length="255" comment="Last Name"/> <column xsi:type="varchar" name="first_name" nullable="false" length="255" comment="First Name"/> <column xsi:type="int" name="age" padding="5" unsigned="true" nullable="false" comment="Age"/> <constraint xsi:type="unique" referenceId="UC_Person"> <column name="id"/> <column name="last_name"/> </constraint> </table> </schema> |
Conclusion:
Using the above code snippet you can easily Create a Unique key Column in the db_schema.xml file of Magento 2.
Lastly, if you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends and Let us know if you are facing any issues while implementing this code.
Fix Unique Constraint Violation Found in Magento 2
Happy Coding!