Magento Join and Left Join function - magento

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'))

Related

Join model between customer entity and custom module

In the Grid.php, I need to join customer/customer model with my custom model.
protected function _prepareCollection() {
$collection = Mage::getResourceModel('customer/customer_collection')->addNameToSelect();
$collection->getSelect()->join(
array('e' => 'event'), 'e.customer_id=main_table.entity_id', array('status')
);
$this->setCollection($collection);
return parent::_prepareCollection();
}
Basically I need to add some more information (in this example is status) to the collection. The event table contains the customer_id as reference to customer_entity.entity_id. How can I do this?
If there is any error you are getting you can share. Meanwhile try below updated code.
protected function _prepareCollection() {
$collection = Mage::getResourceModel('customer/customer_collection')->addNameToSelect();
$collection->getSelect()->join(
array('e' => 'event'), 'e.customer_id=main_table.entity_id', array('e.status') // added 'e.status' in stead of 'status'
);
$this->setCollection($collection);
return parent::_prepareCollection();
}
Hope will help!

use multiple _prepareCollection()'s

Got this code (in: app/code/local/Mage/Adminhtml/Block/Sales/Order/Grid.php):
protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
$collection->getSelect()->join('sales_flat_order_item', '`sales_flat_order_item`.order_id=`main_table`.entity_id', array('skus' => new Zend_Db_Expr('group_concat(`sales_flat_order_item`.sku SEPARATOR "<br>")')))->group('sales_flat_order_item.entity_id');
$collection->getSelect()->join('sales_flat_order_payment', 'main_table.entity_id = sales_flat_order_payment.parent_id',array('method'))->group('sales_flat_order_payment.parent_id');
$this->setCollection($collection);
return parent::_prepareCollection();
}
When I comment the line below COL 1 or COL 2 this works fine, but I want them to work both, how is this done? (if I use them at the same time I get an error: Integrity constraint violation: 1052 Column 'entity_id' in group statement is ambiguous)
UPDATE WITH ANSWER:
protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
$collection->getSelect()->join('sales_flat_order_item', '`sales_flat_order_item`.order_id=`main_table`.entity_id', array('skus' => new Zend_Db_Expr('group_concat(`sales_flat_order_item`.sku SEPARATOR "<br>")')));
$collection->getSelect()->join('sales_flat_order_payment', 'main_table.entity_id = sales_flat_order_payment.parent_id',array('method'))->group('main_table.entity_id');
$this->setCollection($collection);
return parent::_prepareCollection();
}
The answer is in the error, the table to apply the group to cannot be determined. You need to explicitly define the table:
...->group('sales_flat_order_item.entity_id');
echo your query by using echo (string) $collection->getSelect(); You will get a plain sql query here.
Fire that query in database and check, are you getting results the way you want.
Also last but not the least Group also create problem.
Have a look at below link
using group() breaks getSelectCountSql in magento

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: Joining left table in grid

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'
);

Resources