3

Someone can tell me how to filter products by attributes in Sylius. For example I have an attribute color. And I want to get all product they are white.

Thank you

NoNaMe
  • 5,410
  • 30
  • 73
  • 98
binbin
  • 123
  • 1
  • 9

2 Answers2

2

You need to define a custom method in your product repository:

public function findByAttribute($attributeName, $value) 
{
    return $this->getQueryBuilder()
        ->join($this->getAlias() . '.attributes', 'av')
        ->join('av.attribute', 'a')
        ->where('av.value = :value')
        ->andWhere('a.name = :attributeName')
        ->setParameter('attributeName', $attributeName)
        ->setParameter('value', $value)
        ->getQuery()
        ->getResult();
}
gvf
  • 1,009
  • 7
  • 6
0

For Sylius version 1.x

public function findAttributeByChannel(ChannelInterface $channel, string $locale, int $count, int $attributeId): array
{
    return $this->createQueryBuilder('o')
        ->addSelect('translation')
        ->innerJoin('o.translations', 'translation', 'WITH', 'translation.locale = :locale')
        ->innerJoin('o.attributes', 'attribute')
        ->andWhere('attribute.attribute = :attribute_id')
        ->andWhere(':channel MEMBER OF o.channels')
        ->andWhere('o.enabled = true')
        ->addOrderBy('o.createdAt', 'DESC')
        ->setParameter('channel', $channel)
        ->setParameter('locale', $locale)
        ->setParameter('attribute_id', $attributeId)
        ->setMaxResults($count)
        ->getQuery()
        ->getResult()
    ;
}
Code
  • 71
  • 8