I am having seller_id field in my custom table sellerrequest as foreign key. Primary reference is in customer/customer_collection collection. I want to show the seller name in admin grid from the seller_id. I am not sure how to join both collections but I tried with -
$collection = Mage::getModel("wallets/sellerrequest")
->join(
'customer/customer_collection',
'seller_id=main_table.seller_id'
)
->getCollection();
but, it doesn't work. Is this wrong way? Any Help appreciated.
Thanks.
Try this
$collection = Mage::getModel("wallets/sellerrequest")->getCollection();
$collection->getSelect()->joinLeft(
array('cust' => $collection->getTable('customer/customer_collection')),
'cust.seller_id = main_table.seller_id');
Hope this may help.By the way I haven't tried it. But the same worked for me.See the data in the collection to check whether you get the correct data or not.
Here is another example that i have tried.
protected function _prepareCollection(){
$collection = Mage::getModel('children/children')->getCollection();
$collection->getSelect()->joinLeft('schools', 'schools.school_id = main_table.school_id', array('school_name'));
$collection->addFieldToFilter('main_table.customer_id', array('in' => $this->_getCustomer()->getId()));
$this->setCollection($collection);
return parent::_prepareCollection();
}
Here i have joined "schools" table to my children model.In my case the common key between tables is school_id. This worked for me,check this out and make some ammendments to meet your requirement.
Related
I want to join another table with customer grid condition will be custom attribute value and table column value.
I have added one custom attributes for customers, attribute name is affiliate_id, and my other table name is aff_accounts, I want to show the aff_accounts table's column in the customer grid.
Please help me.
Thanks
If you are facing any issue you can ask me.Try the below 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 it will help you.
Good afternoon!
I am a beginner in magento, so have a question connected with getting product collection by manufacturer.
The code I used is bellow:
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('manufacturer');
$collection->addFieldToFilter(array(
array('attribute' => 'manufacturer', 'eq' =>'adidas'),
));
return $collection;
I checked that products with such attribute and value exist, but the size of returned array is 0.
Maybe, I have missed something important with attribute options or something else.
So I will be very thankful for every advice or idea.
If manufacturer dropdown value id is 10 then you can filter like this
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('manufacturer',10);
return $collection;
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
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).
Is it possible in magento to filter user based on the products they have bought?
For eg.
How can I get all the users who have bought product A from category B
mysql query like
SELECT users From table users, table products ..... WHERE user has purchased product A .
Please give some ideas, I needed to make this work.
Thanks
If you want an actual query, you can probably do something as simple as (add additional joins to get customer information from EAV):
SELECT DISTINCT o.customer_id FROM sales_flat_order_item i
INNER JOIN sales_flat_order o ON o.entity_id = i.order_id
WHERE o.customer_id IS NOT NULL
AND i.sku = 'some-product-sku'
Using Magento models, this should work for you:
<?php
require_once 'app/Mage.php';
/*
* Initialize Magento. Older versions may require Mage::app() instead.
*/
Mage::init();
/**
* Get all unique order IDs for items with a particular SKU.
*/
$orderItems = Mage::getResourceModel('sales/order_item_collection')
->addFieldToFilter('sku', 'some-product-sku')
->toArray(array('order_id'));
$orderIds = array_unique(array_map(
function($orderItem) {
return $orderItem['order_id'];
},
$orderItems['items']
));
/**
* Now get all unique customers from the orders of these items.
*/
$orderCollection = Mage::getResourceModel('sales/order_collection')
->addFieldToFilter('entity_id', array('in' => $orderIds))
->addFieldToFilter('customer_id', array('neq' => 'NULL'));
$orderCollection->getSelect()->group('customer_id');
/**
* Now get a customer collection for those customers.
*/
$customerCollection = Mage::getModel('customer/customer')->getCollection()
->addFieldToFilter('entity_id', array('in' => $orderCollection->getColumnValues('customer_id')));
/**
* Traverse the customers like any other collection.
*/
foreach ($customerCollection as $customer) {
var_dump($customer->getData());
}
It's pretty ugly though (instantiates multiple models, executes a bunch of queries under the covers), you could probably write your own model to make this -a lot- prettier.
You have to base your query on orders. If you want to do it by SQL query, you have to it by the following table:
sales_flat_quote, sales_flat_order_item to get the link between customer and product
catalog_category_product to get the link between category and product
catalog_product_entity to get the product id in function of the sku
...
Good luck
try these models
$orders = Mage::getModel('sales/order')->addAttributeToSelect('*')->getCollection();
$order_items = Mage::getResourceModel('sales/order_item_collection')
->addAttributeToSelect('sku')
->addAttributeToSelect('created_at')
->addAttributeToSelect('order_id')
->addAttributeToFilter('order_id', array('in' => $orders_ids))->load();