pspahn
pspahn

Reputation: 2790

Magento - Filter products that have a specific customer group price set (by group code, not id)

I'm looking to filter a product list by those products which have a group_price set at the product level and assigned to a specific customer group.

I was thinking it would be something along the lines of:

$products->addFieldToFilter('group_price', array(
        array(
            'cust_group' => 2
        )
    ));

But it appears that group_price is not an attribute. Additionally, $_product->getGroupPrice() always returns the product's price despite if a group price is set on the product or not.

Ideally, I'd prefer to filter these by the customer group code (ie. Wholesale, Retail, etc) instead of the group id (simply for the case where someone might delete a customer group and recreate it later and the id changes).

Any thoughts?

Upvotes: 2

Views: 2743

Answers (2)

dianovich
dianovich

Reputation: 2287

I have a similar requirement but the problem is that iterating over a large product collection is way too slow.

The catalog_product_index_price table contains group information so you may try something like:

$productCollection = Mage::getModel('catalog/product')->getCollection();
...
$productCollection->addFinalPrice();
$productCollection->getSelect()->where(
    'price_index.customer_group_id = ? AND price_index.group_price IS NOT NULL',
    $customer_group_id
);

Upvotes: 1

pspahn
pspahn

Reputation: 2790

I ended up using this:

    $products = Mage::getModel('catalog/product')->getResourceCollection();
    $products
        ->addAttributeToSelect('*')
        ->addAttributeToFilter('visibility', array('neq' => 1));

    foreach ($products as $product => $value) {

        //still not sure how to get 'group_price' without running load() =(
        $productModel = Mage::getModel('catalog/product')->load($value->getId());
        $groupPrices = $productModel->getData('group_price');

        // A helper of mine
        // store the customer's groupId to compare against available group prices array below.
        $currentGroupId = Mage::helper('user')->getCustomerGroup()->getId();

        // remove products w/o configured group prices
        if (!count($groupPrices)) {
            $products->removeItemByKey($product);
        }
        foreach ($groupPrices as $key) {
            foreach ($key as $subkey => $value) {
                if ($subkey == "cust_group") {
                    $customerGroup = $subkey;
                    if ($value != $currentGroupId) {
                        $products->removeItemByKey($product);
                    }
                }
            }
        }
    };


    $this->_productCollection = $products;
    return $this->_productCollection;

Upvotes: 0

Related Questions