3张桌子之间的Symfony关系

时间:2018-06-22 10:16:15

标签: symfony doctrine

3张桌子:产品,颜色和产品颜色。尝试添加新产品时,我无法在products_colors中插入数据。

产品和products_colors之间的关系是一对多,颜色和products_colors之间的关系是一对多。

颜色始终相同,在我的表单中,可用复选框将可用的颜色选择为color_id。

所以我必须与products_colors表交互以添加/删除元素。...

如何?

文档架构还可以并且可以映射。


这些是我的表单类型:

添加产品表单类型:

    $builder
        ->add('products', CollectionType::class, [
            'entry_type' => ColorsType::class,
            'allow_delete' => true,
            'allow_add' => true,
            'by_reference' => false,
            'prototype' => false
        ])
        ->add('add', SubmitType::class, array('label' => 'Add product'))
    ;

ColorsType:

    $builder
        ->add('color', EntityType::class, array(
            'class' => Colors::class,
            'query_builder' => function(ColorsRepository $repo) {
                return $repo->getColorsRep();
            },
            'choice_value' => function (Colors $entity = null) {
                return $entity ? $entity->getColorsId() : '';
            },
            'choice_label' => function (Colors $entity = null) {
                return $entity ? $entity->getColor() : '';
            },
            'label' => false,
            'required' => false,
            'multiple' => true,
            'expanded' => true,
            'mapped' => true
        ))
    ;

1 个答案:

答案 0 :(得分:0)

您尝试做教义的工作...

当您拥有两个实体时:产品颜色 一个产品可以有多种颜色,并且可以将一种颜色分配给许多产品,因此逻辑上该关系为 ManyToMany

链接这些实体时,Doctrine将创建一个表product_colorcolor_product,它们引用实体之间的每个链接。

product
----------------
id      | name
----------------
1       | Shirt
2       | Skirt


color
----------------
id      | name
----------------
1       | Red
2       | Blue
3       | Green


product_color
------------------------
id_product | id_color
------------------------
1          | 1     # Red shirt
1          | 2     # Blue shirt
2          | 2     # Blue skirt

有关文档https://symfony.com/doc/current/doctrine/associations.html

的更多信息,