【问题标题】:Symfony 2 + Doctrine, joining multiple tablesSymfony 2 + Doctrine,加入多个表
【发布时间】:2016-03-22 13:57:23
【问题描述】:

我有 3 个实体:Products、ProductFeatures(如颜色、尺寸等)和 ProductFeaturesVarient(如红色、橙色、绿色、黄色、32、34、36 等)。

产品可以具有颜色、尺寸等特征。每个特征都可以有变体。喜欢红色、橙色和 32、34 码的 Polo T 恤。

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

因此,第 4 个实体 ProductFeatureVariant 具有以下字段:product_id、feature_id 和 feature_variant_id。

谁能帮我定义这个?

【问题讨论】:

  • 您通常不需要自己创建连接表。使用关系(产品与特征、特征与颜色、特征与尺寸等)
  • 似乎我的表名令人困惑。这是我期望的基本结构 Product: id, Name Features: id, Feature_title FeatureVariant: id, feature_id, variant_title 最终组合表应该看起来像:ProductFeatureVariant:product_id、feature_id 和 variant_id

标签: php symfony doctrine-orm


【解决方案1】:

您只需要 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);

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      • 2014-09-30
      相关资源
      最近更新 更多