【问题标题】:Symfony retrieve Unique values from EAV modelSymfony 从 EAV 模型中检索唯一值
【发布时间】:2020-10-01 22:37:18
【问题描述】:

我正在尝试制作产品过滤器,但无法生成正确的查询

А 快速查看基地 db visually

这是我的实体:

属性类型:

/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string", length=100, nullable=true)
 */
private $name;

/**
 * @ORM\OneToMany(targetEntity=AttributeValue::class, mappedBy="attributeType")
 */
private $attributeValue;

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

属性值:

/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity=Product::class, inversedBy="attributeValues")
 */
private $product;

/**
 * @ORM\Column(type="string", length=100)
 */
private $value;

/**
 * @ORM\ManyToOne(targetEntity=AttributeType::class, inversedBy="attributeValue")
 */
private $attributeType;

例如 AttributeType(Color) 具有 AttributeValue(Red, Blue, Green) 并且我为单个颜色选项检索数百个红色、蓝色、绿色 AttributeValue

该查询返回所有值的选项(不是唯一的):

        return $this->createQueryBuilder('at')
        ->innerJoin('at.attributeValue', 'attribute_value')
        ->addSelect('attribute_value')
        ->getQuery()
        ->getResult();

我尝试这样修改请求:

        return $this->createQueryBuilder('at')
    ->innerJoin('at.attributeValue', 'attribute_value')
    ->addSelect('attribute_value.value')->distinct()
    ->getQuery()
    ->getResult();

(还有其他尝试,但都没有接近)

如何获得每个选项的唯一值?

如果有任何帮助,我将不胜感激

感谢您的宝贵时间。

【问题讨论】:

  • 这是完整的查询构建器构建吗?因为我看不出为什么没有按预期工作的任何原因。
  • 顶部的返回所有值。如果选项中有几个产品的width = 100,我会得到几个100的输出。如果下面的一个甚至没有distinct(),它在选项中只返回一个值

标签: symfony doctrine-orm doctrine symfony4 entity-attribute-value


【解决方案1】:

我得到每个选项的唯一值

    public function findOptionsWithUniqueValue()
{
    $result = $this->getEntityManager()->createQueryBuilder()
        ->addSelect('attribute_type.name, attribute_value.value')
        ->distinct()
        ->from(AttributeType::class,'attribute_type')
        ->from(AttributeValue::class, 'attribute_value')
        ->andWhere('attribute_type.id = attribute_value.attributeType')
        ->getQuery()
        ->getResult()
        ;

    $out = [];
    while( $a = array_shift($result)) {
        $out[$a['name']][] = $a['value'];
    }

    return $out;
}

【讨论】:

    猜你喜欢
    • 2011-04-01
    • 2012-07-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    相关资源
    最近更新 更多