The command dal:create:schema does not create foreign keys

Viewed 67

Given the following example for an Entity-Definition, there is a foreign key defined. As a developer and database engineer i would expect that the command dal:create:schema would also create the expected foreign keys. But this is not the case.

 return new FieldCollection([
    (new IdField('id', 'id'))->addFlags(new PrimaryKey(), new Required()),

    (new LongTextField('comment', 'name'))->addFlags(new Required()),

    (new FkField('order_id', 'orderId', OrderDefinition::class))->addFlags(new Required()),
    new OneToOneAssociationField('order', 'order_id', 'id', OrderDefinition::class, false),

            new CreatedAtField(),
            new UpdatedAtField()
        ]);

Instead this is the result:

CREATE TABLE `order_refund` (
    `id` BINARY(16) NOT NULL,
    `comment` LONGTEXT NOT NULL,
    `order_id` BINARY(16) NOT NULL,
    `created_at` DATETIME(3) NOT NULL,
    `updated_at` DATETIME(3) NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

However, it seems like that ManyToOneAssociations will add foreign keys. Is there something missing in the entity definition?

1 Answers

The command you mentioned is using the SchemaGenerator which has a method to generate Foreign keys:

\Shopware\Core\Framework\DataAbstractionLayer\SchemaGenerator::generateForeignKeys

Looking at this method it seems to work only fields of the type ManyToOneAssociationField

private function generateForeignKeys(EntityDefinition $definition): string
{
    $fields = $definition->getFields()->filter(
        function (Field $field) {
            if (!$field instanceof ManyToOneAssociationField) {
                return false;
            }

            return true;
        }
    );

I also think it is a shortcoming of this function that it does not generate foreign keys for fields of the type OneToOneAssociationField. Maybe you can try to adjust this filtering and see if it works and make a pull request on GitHub for the benefit of yourself and other developers?

Related