Search code examples
vue.jsshopwareshopware6

Insert Many to Many Data into Shopware 6 Database using the Administration


I have created a plugin in the adminstration and I want to insert the manyToMany products with vehicles into Shopware 6 database. From the code below I am trying to insert '92961afbc50e4380b3af86b257630ade' into the 'product_id' column of the 'vehicles_product' table :

import template from './sw-vehicles-import.html.twig';

const { Component, Mixin } = Shopware;

Component.register('sw-vehicles-import', {
    template,
    inject: ['importExport', 'repositoryFactory', 'feature'],

    mixins: [
        Mixin.getByName('notification'),
    ],

    metaInfo() {
        return {
            title: this.$createTitle()
        };
    },

    data() {
        return {
            importFile: null,
            repository: null,
            entity: undefined,
        };
    },
    
    computed: {
    },
     
    created() {
        this.repository = this.repositoryFactory.create('vehicles');
    },

    methods: {
        onStartProcess() {

            this.entity = this.repository.create(Shopware.Context.api);

            this.entity.categoryFilter = 'CategoryName';
            this.entity.featureFilter = 'FeatureName';
            this.entity.products.productId = '92961afbc50e4380b3af86b257630ade';

            this.repository.save(this.entity, Shopware.Context.api);
        }
   }
});

The build process doesn't work, what am I doing wrong? Could you help me please ?


Solution

  • You need to create a new entity collection for the association if it doesn't exist yet.

    const { EntityCollection } = Shopware.Data;
    
    if (!this.entity.products) {
        this.entity.products = new EntityCollection(
            '/product',
            'product',
            Shopware.Context.api
        );
    }
    
    const product = await this.repositoryFactory.create('product').get('92961afbc50e4380b3af86b257630ade', Shopware.Context.api);
    
    this.entity.products.add(product);
    
    this.repository.save(this.entity, Shopware.Context.api);