Search code examples
associationsshopware6

Association with JSON field in Shopware6 entity definition


I have an entity with category_ids as json field, I want to add an association to category entity to get the names of the categories How to do that

This is my entity definition,This ManyToManyAssociationField is not working

protected function defineFields(): FieldCollection
    {
        return new FieldCollection([
            (new IdField('id', 'id'))->addFlags(new Required(), new PrimaryKey()),
            (new StringField('group_name','group_name')),
            (new JsonField('category_ids', 'category_ids'))->addFlags(new Required()),
            (new FkField('shipping_method_id', 'shipping_method_id', ShippingMethodDefinition::class))->addFlags(new Required()),
            (new CreatedAtField()),
            (new UpdatedAtField()),
            (new ManyToOneAssociationField('shippingMethod', 'shipping_method_id', ShippingMethodDefinition::class)),
            new ManyToManyAssociationField('category', CategoryDefinition::class, GroupDefinition::class, 'category_ids', 'id'),
        ]);
    }

Solution

  • Associations within JSON fields are generally not supported. Instead, you need to create a mapping table and a MappingEntityDefinition to handle the association. On how to do that exactly, take a look at the docs.

    If for whatever reason (e.g. faster query performance without a table scan on the mapping table), you additionally need the Ids of the associated entities in a JSON field, you can add an additional ManyToManyIdField and an Indexer that fills this field. Take a look here on how to do that. As an example take a look at the SalesChannelIndexer from the core, that populates the paymentMethodIds field for every sales channel.