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
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();
}
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()
;
}