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.
Move to the below path
app\code\Vendor\Extension\etc\db_schema.xml
And add the code as given below
<?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>
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!
Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…
MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…
In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…
Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…
The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…
Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…