symfonysymfony5sylius

Override Doctrine constraint UniqueConstraint


I'm working on a project where I'm using Sylius. I have to override a default constraint related to the ChannelPricing entity.

Here is the original constraint declaration: The link to the original file :
https://github.com/Sylius/Sylius/blob/v1.10.7/src/Sylius/Bundle/CoreBundle/Resources/config/doctrine/model/ChannelPricing.orm.xml

    <mapped-superclass name="Sylius\Component\Core\Model\ChannelPricing" table="sylius_channel_pricing">
        <unique-constraints>
            <unique-constraint columns="product_variant_id,channel_code" name="product_variant_channel_idx" />
        </unique-constraints>
    </mapped-superclass>

I was able to create a migration with my new constraint when I use the annotation @UniqueEntity on the extended entity class:

/**
 * @ORM\Entity
 * @ORM\Table(
 *     name="sylius_channel_pricing",
 *     uniqueConstraints={@UniqueConstraint(
 *     name="product_variant_channel_customer_group_idx",
 *     columns={"product_variant_id", "channel_code", "customerGroup_id"})},
 * )
 */
class ChannelPricing extends BaseChannelPricing

But... these lines only generates a migration to create the constraint product_variant_channel_customer_group_idx.. I want to tell Doctrine that I want to drop the default constraint product_variant_channel_idx first


Solution

  • My mistake was to defined a new name for the constraint. If I use the original, Doctrine understand that I want to make an override and generate the drop instruction.

    So, for these annotations :

    /**
     * @ORM\Entity
     * @ORM\Table(
     *     name="sylius_channel_pricing",
     *     uniqueConstraints={@UniqueConstraint(
     *     name="product_variant_channel_idx",
     *     columns={"product_variant_id", "channel_code", "customerGroup_id"})},
     * )
     */
    class ChannelPricing extends BaseChannelPricing
    {
    

    The generated migration :

    public function up(Schema $schema): void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->addSql('DROP INDEX product_variant_channel_idx ON sylius_channel_pricing');
        $this->addSql('CREATE UNIQUE INDEX product_variant_channel_idx ON sylius_channel_pricing (product_variant_id, channel_code, customerGroup_id)');
    }