Symfony 2 + Doctrine,加入多个表格

时间:2016-03-22 13:57:24

标签: php symfony doctrine-orm

我有3个实体:Products,ProductFeatures(如Color,Size等)和ProductFeaturesVarient(如红色,橙色,绿色,黄色,32,34,36等)。

产品可以具有颜色,尺寸等功能。每个功能都可以有变体。像马球T恤,红色,橙色和32,34尺寸。

我想通过连接表来关联这3个实体。我知道我必须创建一个类似于ProductFeatureVariant的实体,但我不知道如何定义关系。

所以,第四个实体ProductFeatureVariant包含字段:product_id,feature_id和feature_variant_id。

有人可以帮我定义吗?

2 个答案:

答案 0 :(得分:0)

您只需要3个一对多关系,这可以是双向的。

/** @Entity */
class Product
{
    /** @Column(type="integer") */
    private $id;
    /** @Column(length=140) */
    private $name;
    /**
     * @OneToMany(targetEntity="ProductFeature", mappedBy="product")
     */
    private $features;

    public function __construct() {
        $this->features = new ArrayCollection();
    }
}

/** @Entity */
class ProductFeature
{
    /** @Column(type="integer") */
    private $id;
    /** @Column(length=140) */
    private $name;
    /**
     * @ManyToOne(targetEntity="Product", inversedBy="features")
     * @JoinColumn(name="product_id", referencedColumnName="id")
     */
    private $product;
    /**
     * @OneToMany(targetEntity="ProductFeatureVariant", mappedBy="productFeature")
     */
    private $variants;

    public function __construct() {
        $this->variants = new ArrayCollection();
    }
}

/** @Entity */
class ProductFeatureVariant
{
    /** @Column(type="integer") */
    private $id;
    /** @Column(length=140) */
    private $name;
    /**
     * @ManyToOne(targetEntity="ProductFeature", inversedBy="variants")
     * @JoinColumn(name="product_id", referencedColumnName="id")
     */
    private $productFeature;
}

使用查询构建器可以进行简单的连接。

//select products with a certain color
$qb = $this->entityManager->createQueryBuilder();
$qb
    ->select('p')
    ->from('Product', 'p')
    ->leftJoin('p.features', 'f')
    ->leftJoin('f.variants', 'v')
    ->where('v.name = :color')
    ->setParameter('color', $color);

答案 1 :(得分:0)

由于ProductFeaturesVariant已经链接到ProductFeatures,我将避免对ProductFeatures表的引用,因此它只是Product和ProductFeaturesVariant表之间的ManyToMany关系。如果您将ProductFeaturesVariant重新分配给其他功能,则您的三重链接表将变得不一致。