Daniel Bohusz
Daniel Bohusz

Reputation: 1

Shopware ManyToMany with additional field

I'm looking for a solution how to properly add field "priority" in jon table between products and faqs. This is relation ManyToMany.

All of my attempts to write this field using VueJS lead to the error message: Expected command for "xxx" to be "Shopware\Core\Framework\DataAbstractionLayer\Write\Command\UpdateCommand". (Got: Shopware\Core\Framework\DataAbstractionLayer\Write\Command\InsertCommand)

 CREATE TABLE `sample_product_faq` (
                `id` BINARY(16) NOT NULL,
                `product_id` BINARY(16) NOT NULL,
                `product_version_id` BINARY(16) NOT NULL,
                `faq_id` BINARY(16) NOT NULL,
                `priority` int(11) unsigned NOT NULL DEFAULT 0,
                `created_at` datetime(3) NOT NULL,
                `updated_at` datetime(3) DEFAULT NULL,
                PRIMARY KEY (`id`),
                CONSTRAINT `fk.product_faq.faq_id` FOREIGN KEY (`faq_id`)
                REFERENCES `sample_faq` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
                CONSTRAINT `fk.product_faq.product_id` FOREIGN KEY (`product_id`, `product_version_id`)
                REFERENCES `product` (`id`, `version_id`) ON DELETE CASCADE ON UPDATE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Upvotes: 0

Views: 220

Answers (1)

dneustadt
dneustadt

Reputation: 13161

You're trying to create (insert) a new record when there already is an existing record with the same primary key(s). That's why it expects you to update the existing record instead.

You need to try and fetch the existing record and either return the existing record or a new one.

// ...
inject: ['repositoryFactory'],

computed: {
    repository() {
        return this.repositoryFactory.create('sample_product_faq');
    },
},

methods: {
    async fetchOrCreate(id) {
        const existing = await this.repository.get(id, Shopware.Context.api);

        if (existing) {
            return existing;
        }

        return this.repository.create(Shopware.Context.api);
    },
},

You can also check beforehand whether a given entity is supposed to created or updated:

entity.isNew()

For the sake of completion I will say that you can force an update by setting entity._isNew = false but it is discouraged as it could lead to data loss, hence why the property is considered private.

Upvotes: -1

Related Questions