5

I want to create custom filed say myname with constraints UNIQUE KEY in custom extension table.

In Magento1 we can define like this :

UNIQUE KEY `myname` (`myname`)

How can I do this in Magento2?

20

You can use Index Type as \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
To add unique key use code,

->addIndex(
    $installer->getIdxName(
        'YOUR_TABLE_NAME',
        ['YOUR_UNIQUE_FIELD_NAME'],
        \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
    ),
    ['YOUR_UNIQUE_FIELD_NAME'],
    ['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)

You can add multiple column combination as UNIQUE with,

->addIndex(
    $installer->getIdxName(
        'catalog_product_entity_datetime',
        ['entity_id', 'attribute_id', 'store_id'],
        \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
    ),
    ['entity_id', 'attribute_id', 'store_id'],
    ['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)

Refer vendor\magento\module-catalog\Setup\InstallSchema.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.