Magento: Joining left table in grid - magento

I am trying to add a grid in which I need to do a left join.
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('admin/user_collection')->join("school/school",'ref_id = referer_id',"school_name",**"left"**);
var_dump((string)$collection->getSelect());
$this->setCollection($collection);
return parent::_prepareCollection();
}
Even though I have defined "left" when I see the dump it shows:
SELECT main_table.*, school/school.school_name FROM admin_user AS main_table INNER JOIN school AS school/school ON ref_id = referer_id
I tried to do a
$collection = Mage::getResourceModel('admin/user_collection')->**joinLeft**("school/school",'ref_id = referer_id',"school_name","left"); but for which my system does not show me any var_dump hangs.

try getSelect() before the join

with product collection if you want to place OR condition bw the attributes
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter(
array(
array('attribute'=>'my_attribute', 'eq'=>'0'),
array('attribute'=>'my_other_attribute', 'neq'=>'0')
),
'',
'left'
);

Related

Magento Join and Left Join function

is there anyway that i can join groupdeals/coupon table to my grid collection?
this is my prepare collection function
protected function _prepareCollection()
{
$orderIds = Mage::getModel('sales/order_item')->getCollection()->addFieldToFilter('product_id', $this->getRequest()->getParam('id'))->getColumnValues('order_id');
$collection = Mage::getResourceModel('sales/order_grid_collection')->addAttributeToFilter('entity_id', array('in' => $orderIds));
$this->setCollection($collection);
return parent::_prepareCollection();
}
now i want it to join with groupon_coupons table
i want to join the tables so that i can filter Coupon code and security code from my order Grid.
add this line to collection ->join(array('tblalias' => 'tablename'),'main_table.fildname = tblalias.fildname',array('fildfromsecondtable' => 'tblalias.filedname'))

Magento - Select stock status in category->getProductCollection

I am trying to get the stock status of all products within a particular category. My current code is below but getIsInStock is not part of the default collection. How can i get this value in the same way as ->addAttributeToSelect('product_type')
$collection = Mage::getModel('catalog/category')->load($_cat_id)->getProductCollection()
->addAttributeToSelect('product_type');
foreach ($collection as $product) {
if( $product->getIsInStock() ) {
print $product->getProductType().' is in stock';
}
}
You can join your collection by :
$collection->joinField(
'is_in_stock',
'cataloginventory/stock_item',
'is_in_stock',
'product_id=entity_id',
'{{table}}.stock_id=1',
'left'
)
let me know if it helpes

How to exclude a category from a magento getCollection

this might be a silly question, but well. I have the following code that retrieves all the products on my shop.
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToFilter('status', 1);
$products->addAttributeToFilter('visibility', 4);
$products->addAttributeToFilter('type_id', 'simple');
$products->addAttributeToSelect('*');
$products->addStoreFilter($storeId);
$prodIds = $products->getAllIds();
Im aware of the:
$category = Mage::getModel('catalog/category')->load(9);
$products->addCategoryFilter($category);
to filter by a category ID, but how to get all products except one specific category ID ? (Magento 1.6.2)
I think this should work, presuming you know what category ID you want to filter out, but I can't test it right now
$catId = 9;
/* I'm almost positive 'e' is the alias used for catalog_product_entity, check your
query with echo (string) $products->getSelect(); if it doesn't work */
$products->getSelect()->join(array('cats' => 'catalog_category_product'), 'cats.product_id = e.entity_id');
$products->getSelect()->where('cats.category_id', array('neq' => $catId));
This is what I used:
$_productCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addUrlRewrite();
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($_productCollection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($_productCollection);
$_productCollection->load();
$_productCollection->getSelect()->join(array('cats' => 'catalog_category_product'), 'cats.product_id = e.entity_id');
$_productCollection->getSelect()->where('cats.category_id not in (41)');
Here is the logic I came up with to resolve this problem.
Note: Should work in Magento 1.X
It dynamically pulls table names so that it would work in any installation.
It validates that it is a correct catalog/category entity ID.
It uses a unique table alias by category ID when performing the MySQL LEFT JOIN. This allows us to exclude the collection from multiple category IDs.
It validates that we do not attempt to exclude the collection from the same category id twice.
public function addCategoryExclusionFilter(Mage_Catalog_Model_Resource_Product_Collection $collection, $category_id)
{
/* #var $resource Mage_Core_Model_Resource */
/* #var $category Mage_Catalog_Model_Category */
$resource = Mage::getModel('core/resource');
$category = Mage::getModel('catalog/category')->load($category_id);
$select = $collection->getSelect();
$tblccp = $resource->getTableName('catalog_category_product');
$tblAlias = $tblccp.'_'.$category_id;
if (! $category->getId()) {
Mage::throwException("Invalid `{$resource->getTableName('catalog/category')}`.`entity_id` value ({$category_id}).");
}
if (strpos($select->__toString(), $tblAlias) !== false) {
Mage::throwException("Category (ID: {$category->getId()}) already excluded from collection");
}
$select->joinLeft(array($tblAlias => $tblccp), "(`{$tblAlias}`.`product_id` = `e`.`entity_id` AND `{$tblAlias}`.`category_id` = '{$category->getId()}')", array());
$select->where("`{$tblAlias}`.`category_id` IS NULL");
}
Example of the MySQL query afterwards:
SELECT
`e`.*
FROM
`catalog_product_entity` AS `e`
LEFT JOIN
`catalog_category_product` AS `catalog_category_product_28` ON (
`catalog_category_product_28`.`product_id` = `e`.`entity_id` AND
`catalog_category_product_28`.`category_id` = '28'
)
WHERE
(`catalog_category_product_28`.`category_id` IS NULL)
What we are doing here is performing a join on the table which holds the relationship between product entities and category entities, BUT only where the record's category_id is equal to the category id which we are looking to exclude. This is important because the catalog_product_entity table has a 1:M relationship to the catalog_category_product table (at the time of posting this answer, I do not see the other answers here addressing this). Then, we add a WHERE declaration that we only want to select records where the category_id column for the joined table IS NULL (because there exists no record in the joined table, for product entities which we wish to select).

Better way to add attribute to collection

I am overriding the Mage/Adminhtml/Sales/Order/Grid.php and adding some data to the prepareCollection. This is how I got the customer EAV Attribute campaign_id to be included in the collection, but it is kind of hacky. I was wondering if there was a better way.
protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
foreach ($collection as &$object){
$customer = Mage::getModel('customer/customer')
->setId($object->getCustomerId())
->load();
$object->setCampaignId($customer->getCampaignId());
}
$this->setCollection($collection);
return parent::_prepareCollection();
}
You'll need to join the data from customer records onto the order collection before its loaded.
You can observe the collection before & after load events. For sales/order_grid_collection collection these events are sales_order_grid_collection_load_before and sales_order_grid_collection_load_after - you'll want to use the former. The collection can be accessed in your _before_load event observer via $observer->getOrderGridCollection().
protected function _prepareCollection() {
$collection = Mage::getResourceModel($this->_getCollectionClass());
$class = get_class($collection);
$attribute = Mage::getModel('eav/config')
->getAttribute('customer', 'campaign_id');
$attributeId = $attribute->getAttributeId();
$backendType = $attribute->getBackendType(); //probably varchar
$tableName = Mage::getSingleton('core/resource')
->getTableName('customer_entity_' . $backendType);
$collection->getSelect()
->joinLeft(array('v' => $tableName),
'main_table.customer_id = v.entity_id AND attribute_id = 153',
array('v.value', 'v.attribute_id'));
$this->setCollection($collection);
return parent::_prepareCollection();
}

Magento: fetching manufacturer/brand from database

I have this code from Mukesh Chapagain: link here
$_product = Mage::getModel('catalog/product')->load(PRODUCT_ID);
$manufacturerName = $_product->getAttributeText('manufacturer');
$manufacturerId = $_product->getManufacturer();
This seems not to pick up the manufacturers even though I have them as attributes. Is it due to the fact that the manufacturer field is a drop-down?
any help in getting manufacturer attribute will be appreciated
To retrieve all Manufactures
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'manufacturer');
foreach ( $attribute->getSource()->getAllOptions(true, true) as $option){
$attributeArray[$option['value']] = $option['label'];
}
foreach($attributeArray as $key=>$val){
echo $val;
}
Get products from Manufactures
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('manufacturer');
$collection->addFieldToFilter(array(
array('attribute' => 'manufacturer', 'eq' =>$designer_id),
));
Get selected manufacturer to products
$_productCollection=$this->getLoadedProductCollection();
foreach ($_productCollection as $_product):
echo $_product->getAttributeText('manufacturer');
endforeach;
Honestly, I cannot tell what is wrong with the code in question.
However I have recently been working on something related - if you're trying to use a collection of products. Rather than trying to fix something which probably isn't broken, think of this as an alternative suggestion.
To start with you would need to download my library of query patterns. It contains a class for drop-down attributes. The following adds a manufacturer_text column to the collection.
$products = Mage::getResourceModel('catalog/product_collection');
Knectar_Select_Product_Values::enhanceProducts($products, 'manufacturer');
foreach ($products as $product) {
echo $product->getManufacturerText(), '<br>';
}
This work for me:
SELECT
CPEI.entity_id,
CPE.sku,
CPEI.attribute_id,
EA.attribute_code,
CPEI.value AS value_id,
EAOV.value
FROM
catalog_product_entity_int AS CPEI
INNER JOIN eav_attribute_option_value AS EAOV ON (EAOV.option_id = CPEI.value AND EAOV.store_id = CPEI.store_id)
INNER JOIN catalog_product_entity AS CPE USING(entity_id)
INNER JOIN eav_attribute_option AS EAO USING(option_id)
INNER JOIN eav_attribute AS EA ON(CPEI.attribute_id = EA.attribute_id)
WHERE
(
CPEI.value IS NOT NULL AND
EA.attribute_code = 'manufacturer' AND
CPEI.store_id = 0
);

Resources