Which way is better to load models in magento? - magento

I don't know if i am asking that right.I need to load a product, change some values and save it. My question is which way is the appropriate to do it.Currently i am using that way:
$id = Mage::getModel('catalog/product')->getIdBySku($sku);
$product = Mage::getModel('catalog/product')->load($id);
1) In general it works fine even with 40K products.But i read that this way is leading to memory leak? Also for that solution i read that if i disable the reindex functionality i can improve the process time.
2) If i use another way and load it as a collection and then apply some filters, ex addFieldToFilter('sku',$the_product_i_want)
would be better?
When i say better i mean: 1)the magento way, 2)time efficient 3)not doing something that i don't need to do.

Each time you call the following code snippet Mage::getModel('catalog/product') Magento will create a new model object in the memory. And that will lead to memory wastage. You can do as follows.
$model = Mage::getModel('catalog/product');
$id = $model->getIdBySku($sku);
$product = $model->load($id);
At the same time if you have the product object you can use the following code.
$collection = Mage::getModel('catalog/product')->getCollection();
$product = $collection->addFieldToFilter('sku',$the_product_i_want);

Related

How can I sort a loaded product collection in Magento?

I want to sort a product collection that is already loaded by
$_productCollection = $this->getLoadedProductCollection();
The default sort in admin Magento is Style attribute
I want to sort first by Style, then by color and then by name.
I've try
$_productCollection->setOrder(array('style', 'color','name'), asc);
and also
$_productCollection->addAttributeToSort('color', Varien_Data_Collection::SORT_ORDER_ASC);
$_productCollection->addAttributeToSort('name', Varien_Data_Collection::SORT_ORDER_ASC);
but is not working.
The default sort is working good. Can someone please help?
You can do it this way:
$_productCollection = $this->getLoadedProductCollection();
$_productCollection->clear();
$_productCollection->addAttributeToSort('color', Varien_Data_Collection::SORT_ORDER_ASC);
foreach ($_productCollection as $product) {
// ...
}
This way the collection is forced to be reloaded and then your custom sorting is applied.
You can also take clone of the loaded collection and then modify the query as you want.
// clone of the current collection.Better way of modifying the colection
$_productCollection = clone $this->getLoadedProductCollection();
// unset the cuurent coolection and append your custom filter.
$_productCollection->clear()
->addAttributeToFilter('color', Varien_Data_Collection::SORT_ORDER_ASC)
->load();
Nothing here or elsewhere worked for me. No matter what I tried it would just not sort on /Magento_Catalog/templates/product/list.phtml using 'getLoadedProductCollection()'. Also had a weird issue where products would disappear after clearing cache, until a reindex was done. No idea what was going on there, something was not right.
So I got it to work in the hacky way below (Yes I know it's not 'best practice' to use object manager but it was the only thing that worked!!)
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryId = 2;
$category = $_objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);
$productCollection = $_objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$_productCollection = $productCollection->create()
->addAttributeToSelect('*')
->setOrder('position', 'ASC')
->addCategoryFilter($category)->load();
If you have products in a collection that need more advanced sorting/oordering you can move the products to an assoc array which is much easier to sort/order as you like. Once the order is as you like you can add them back by first clearing your collection with $collection-removeAllItems() and then iterate your array as $product and move each product back to the collection with $collection->addItem($product);
I used this when I wanted a sticky that was not touched by different ordering/sorting.
You can use setOrder on collection to sort any collection data like below :
$_productCollection->setOrder('id','DESC');
Where id can be replace with your column name, & second parameter can be DESC & ASC as per your requirement.
Have it working in v2.3.7 using the following
$_productCollection = $block->getLoadedProductCollection();
$_productCollection->getSelect()->reset(Zend_Db_Select::ORDER);
$_productCollection->setOrder('price', 'ASC');

Programmatically modify related products in magento

I'm trying to programmatically manipulate the product relations in a Magento store.
From what I've read, setRelatedLinkData should be the way to go.
As I simple test, I'm just trying to replace a products related products with nothing (i.e. an empty array), however it's not working - the product in question is still showing the related product in the backend.
The test code I'm working with is:
$product = Mage::getModel('catalog/product')->load($product->getId());
$linkData = array();
print_r($linkData);
$product->setRelatedLinkData($linkData);
echo "Save\n";
$r = $product->save();
As mentioned above however the product still has a related product when I reload it in the backend.
NOTE: I don't only want to remove related products, eventually I want to be able to add new ones as well, so a DELTE FROM... SQL query isn't what I am looking for. However if I can't get it to work to remove products, then it's certainly not going to work to add them, so one step at a time :-)
The quickest way I can think of is to use the Link Resource:
app/code/core/Mage/Catalog/Model/Resource/Product/Link.php saveProductLinks
// sample code
$product = Mage::getModel('catalog/product')->load(147);
$linkData = array();
Mage::getResourceModel('catalog/product_link')->saveProductLinks(
$product, $linkData, Mage_Catalog_Model_Product_Link::LINK_TYPE_RELATED
);
and if you want to assign products use the same code but provide this as $linkData:
$linkData = array(
'145' => array('position' => 1),
'146' => array('position' => 2)
);

How To Efficiently Loop Through Product Collection and Set Attribute Data

I am trying to bulk update some of my product attributes. Effectively I am using this code:
foreach ($outOfStock as $product) {
$product->setData('attribute',20);
$product->save();
}
However I am getting a php 60 second timeout, when I check, it only got as far as about 15 products. It seems to me that this is not the most efficient way to achieve this.
What is the correct way to update products in bulk?
If your attribute is mass-updatable, you may refer to the corresponding core code from Mage_Adminhtml_Catalog_Product_Action_AttributeController::saveAction(), especially this method :
Mage::getSingleton('catalog/product_action')
->updateAttributes($productsIds, $attributesData, $storeId);

Magento: Updating Product Catalogs faster

I have written quite a few scripts to update my product catalog based on some or other parameter. In each of them the base logic is something simillar to this...
//Get collection
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('sku');
$collection->addAttributeToSelect('publihser');
$collection->addFieldToFilter(array(array('attribute'=>'publisher','eq'=>$publisher)));
// for each product in collection do a individual save
foreach ($collection as $product) {
$product->setSKU($newValue);
$product->save();
}
Though this work, each save is a SQL update query and the fact is that having a very large catalog, this is fairly slow.
I was wondering if this could be sped up by doing single save on the collection instead on the product.
There are several things you can do to write a much faster update script. I don't know how you are getting some of your variables so you'll need to modify to get it working in your case, but the code below should be much faster than the way you are currently doing it. e.g:
// Set indexing to manual before starting updates, otherwise it'll continually get slower as you update
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL));
$processes->walk('save');
// Get Collection
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('sku')
->addAttributeToSelect('publihser')
->addFieldToFilter(array(array('attribute'=>'publisher','eq'=>$publisher)));
function productUpdateCallback($args){
$product = Mage::getModel('catalog/product');
$product->setData($args['row']);
$productId = $product->getId();
$sku = 'yourSku';
// Updates a single attribute, much faster than calling a full product save
Mage::getSingleton('catalog/product_action')
->updateAttributes(array($productId), array('sku' => $sku), 0);
}
// Walk through collection, for large collections this is much faster than using foreach
Mage::getSingleton('core/resource_iterator')->walk($collection->getSelect(), array('productUpdateCallback'));
// Reindex all
$processes->walk('reindexAll');
// Set indexing back to realtime, if you have it set to manual normally you can comment this line out
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME));
$processes->walk('save');

Magento Product Insert Function

I need to add a custom option to all products as they get saved. For that I need to find the function that inserts the products into the database, which I'm not able to find.
Please, any help would be appreciated.
thanx
$client = new SoapClient('http://www.magentolocal.it/api/?wsdl');
$session = $client->login('productloader', '1234567890');
$sku = "123456";
$attrs['name'] = "Template #1";
$attrs['description'] = "This is the first template.";
$attrs['short_description'] = "This is the short description of the template";
$attrs['websites'] = array('1');
$attrs['price'] = "11.53";
$attrs['categories'] = array('35');
$attrs['images'] = array()
$result = $client->call($session, 'catalog_product.create', array('simple', '63', $sku, $attrs));
echo $result;
$client->endSession($session);
Magento's EAV system is pretty strung out among several files, so you won't find a single function that accomplishes what you want. If you did go looking for it, and changed it, you would also be changing the same save method that mostly every other object in Magento uses, which is probably not what you want.
To do what you want, try setting up an observer/listener on the events that catalog products use when saving, namely catalog_product_save_before or catalog_product_save_after. That way, you don't have to hack the framework.
Hope that helps!
Thanks,
Joe
How about http://www.magentocommerce.com/wiki/doc/webservices-api/api/catalog_product#catalog_product.create?

Resources