I am having an issue while saving a product in Magento.
I have a product and have multiple stores (multiple groups and views).
Example Website
Store Group 1
English
French
German
Store Group 2
Bangla
Hindi
Say I am editing the product for store French and clicked on save. But the thing is, the newly saved/entered value for store French is copied to all stores (English, German, etc.).
I need to save the values (even for price values) only for specified stores. Not to all of the stores.
If the solution is a programmatic way, I agree to go with that.
Thanks
Newly Added:
I also want to know about saving price, cost, special price, grouped price, tier price
before saving set the storeId of the store you want to save the product for, same is working with loading a product
$product->setStoreId('2')->setName('Name for Store 2')->save();
$product->setStoreId('2')->load(17)->getName()
good luck!
I have solved the price, cost, special price, grouped price, tier price saving issues myself.
I searched on Google and got an extension called Store View Pricing for free. That solved my 80% of the problem. It just gives the opportunity to save prices on a per store basis.
But, to make the other fields (cost, special price, grouped price, tier price) also behave like the price field/attribute, I needed to change the Scope (is_global: column name at DB) to Store View (0: set to DB). I did run the following query on DB:
SELECT ea.attribute_id, ea.entity_type_id, ea.attribute_code, ea.frontend_label, cea.is_global
FROM `eav_attribute` AS ea
INNER JOIN `catalog_eav_attribute` AS cea ON ea.attribute_id = cea.attribute_id
WHERE `attribute_code` LIKE '%price%'
ORDER BY ea.`attribute_id` ASC
I found the attributes what I needed. And changed the is_global value of them to 0.
After doing so, all is working fine as I need. I know this kinda manual process. I am trying to get a programmatic solution.
I had this issue in 1.5
i overide app\code\core\Mage\Catalog\Model\Resource\Eav\Mysql4\Abstract.php
protected function _insertAttribute($object, $attribute, $value) {
/**
* save required attributes in global scope every time if store id different from default
*/
$storeId = Mage::app()->getStore($object->getStoreId())->getId();
if ($attribute->getIsRequired() && $this->getDefaultStoreId() != $storeId) {
$bind = array(
'entity_type_id' => $attribute->getEntityTypeId(),
'attribute_id' => $attribute->getAttributeId(),
'store_id' => $this->getDefaultStoreId(),
'entity_id' => $object->getEntityId(),
'value' => $this->_prepareValueForSave($value, $attribute)
);
$this->_getWriteAdapter()->insertOnDuplicate($attribute->getBackend()->getTable(), $bind, array('value'));
}
to
protected function _insertAttribute($object, $attribute, $value) {
/**
* save required attributes in global scope every time if store id different from default
*/
$storeId = Mage::app()->getStore($object->getStoreId())->getId();
if ($attribute->getIsRequired() && $this->getDefaultStoreId() != $storeId) {
$table = $attribute->getBackend()->getTable();
$select = $this->_getReadAdapter()->select()
->from($table)
->where('entity_type_id = ?', $attribute->getEntityTypeId())
->where('attribute_id = ?', $attribute->getAttributeId())
->where('store_id = ?', $this->getDefaultStoreId())
->where('entity_id = ?', $object->getEntityId());
$row = $this->_getReadAdapter()->fetchOne($select);
if (!$row) {
$bind = array(
'entity_type_id' => $attribute->getEntityTypeId(),
'attribute_id' => $attribute->getAttributeId(),
'store_id' => $this->getDefaultStoreId(),
'entity_id' => $object->getEntityId(),
'value' => $this->_prepareValueForSave($value, $attribute)
);
$this->_getWriteAdapter()->insertOnDuplicate($attribute->getBackend()->getTable(), $bind, array('value'));
}
}
Related
I am trying to edit the Orders Grid so that I can export data to XML with the quantity of each item sold on each line.
Now I can only access the total amount of the order, which is not sufficient. I would like to build a Grid with the information available for each order in Order View > Information > Ordered items.
Is this possible with a few lines of code ?
Here is what I did for now :
I tried to manually add columns in the _prepareColumns() function from Grid.php.
Basically, I tried to add a quantity column :
$this->addColumn('total_qty_ordered', array(
'header' => Mage::helper('sales')->__('Qty'),
'index' => 'total_qty_ordered',
'filter_index' => 'sales_flat_order.total_qty_ordered',
));
However I do not get any total quantity, and of course I do not get the product split in each order. I do not really know where to look to implement this product split.
Thanks by advance.
EDIT :
Here is what is I get thanks to the extension
Order grid
However, I cannot export this product split because the last column is a kind of 'embedded' of other information. So I get an empty column in XML.
I don't usually recommend extensions -- I believe most of them can be a bit more trouble than they are worth, but in this case, I do recommend this one:
http://www.magentocommerce.com/magento-connect/enhanced-admin-grids-editor.html
It's free -- code is fairly clean and you can add that by clicking the grid customization button on the orders page, clicking more options, then finding the items drop down and adding those columns in. Will show you a table of all of the items.
If you want to post the code you've written the custom way, I can help you customize that to do the job too.
We published a whole blog post on how to add any data to your order grid. Hope this will help you! https://grafzahl-io.blogspot.de/2016/11/how-to-display-m2e-order-data-or.html
So the solution would be to copy the Sales Grid Block to a local module and add your column like this example:
$this->addColumn('order_type', array(
'header' => Mage::helper('sales')->__('Order Type'),
'width' => '100px',
'align' => 'left',
'index' => 'order_type',
'renderer' => 'yourmodule/adminhtml_sales_grid_renderer_m2eAttribute',
'filter_condition_callback' => array($this, '_filterM2eConditionCallback')
));
The filter_condition_callback is a method in the Grid Block. The renderer is another class as you can see in the namespace. In the renderer you can define what is displayed in your column. The filter_condition_callback defines how the grid should act, in case someone will filter by your custom column.
It will look like this:
/**
* filter callback to find the order_type
* of orders through m2e (amazon, ebay, ...)
*
* #param object $collection
* #param object $column
* #return Yourname_Yourmodule_Block_Adminhtml_Sales_Order_Grid
*/
public function _filterM2eConditionCallback($collection, $column) {
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
if (!empty($value) && strtolower($value) != 'magento') {
$this->getCollection()->getSelect()
// join to the m2mepro order table and select component_mode
->join(
'm2epro_order',
'main_table.entity_id=m2epro_order.magento_order_id',
array('component_mode')
)
->where(
'm2epro_order.component_mode = "' . strtolower($value) . '"');
} elseif(strtolower($value) == 'magento') {
$this->getCollection()->getSelect()
->join(
'm2epro_order',
'main_table.entity_id=m2epro_order.magento_order_id',
array('component_mode')
)
->where(
'm2epro_order.component_mode = NULL');
}
return $this;
}
As you can see, there are two joins to collect the data we need to filter for.
This is how the renderer looks like which will display the data in the grid:
class Yourname_Yourmodule_Block_Adminhtml_Sales_Grid_Renderer_M2eAttribute
extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
public function render(Varien_Object $row)
{
// do whatever you need, to display your data
// get the id of the row order data
$orderId = $row->getEntityId();
// get the related m2e order data
$orders = Mage::getModel('M2ePro/Order')
->getCollection()
->addFieldToSelect('component_mode')
->addFieldToFilter('magento_order_id', $orderId);
if($orders) {
$data = $orders->getFirstItem()->getData();
if(isset($data['component_mode'])) {
return ucfirst($data['component_mode']);
}
}
// return the string "magento" if there is no m2e relation
return 'Magento';
}
}
The link will show you other example, how to show data in the order grid.
I am looking to add a column to the product grid (in the admin area to be clear) to display how many times this product has been sold. Here is what I have so far after piecing together from several other posts:
In app/code/local/Namespace/Qtysold/Block/Adminhtml/Catalog/Product/Grid.php
<?php
class Namespace_Qtysold_Block_Adminhtml_Catalog_Product_Grid extends Mage_Adminhtml_Block_Catalog_Product_Grid
{
/* Overwritten to be able to add custom columns to the product grid. Normally
* one would overwrite the function _prepareCollection, but it won't work because
* you have to call parent::_prepareCollection() first to get the collection.
*
* But since parent::_prepareCollection() also finishes the collection, the
* joins and attributes to select added in the overwritten _prepareCollection()
* are 'forgotten'.
*
* By overwriting setCollection (which is called in parent::_prepareCollection()),
* we are able to add the join and/or attribute select in a proper way.
*
*/
public function setCollection($collection)
{
/* #var $collection Mage_Catalog_Model_Resource_Product_Collection */
$store = $this->_getStore();
if ($store->getId() && !isset($this->_joinAttributes['qty_sold'])) {
$collection->joinAttribute(
'qty_sold',
'reports/product_collection',
'entity_id',
null,
'left',
$store->getId()
);
}
else {
$collection->addAttributeToSelect('qty_sold');
}
echo "<pre>";
var_dump((string) $collection->getSelect());
echo "</pre>";
parent::setCollection($collection);
}
protected function _prepareColumns()
{
$store = $this->_getStore();
$this->addColumnAfter('qty_sold',
array(
'header'=> Mage::helper('catalog')->__('Qty Sold'),
'type' => 'number',
'index' => 'qty_sold',
),
'price'
);
return parent::_prepareColumns();
}
}
A couple of things here. 1) $store->getId() returns 0 so it never goes into that first block in setCollection, is that correct behavior since it is the Admin area? 2) If I force the joinAttribute to run, it causes an exception (Invalid entity...) which is sort of expected since reports doesn't appear to really be an entity, but I'm not really clear on this whole entity business. 3) In other examples (like this one: http://www.creativemediagroup.net/creative-media-web-services/magento-blog/30-show-quantity-sold-on-product-page-magento) they use something like this:
$_productCollection = Mage::getResourceModel('reports/product_collection')
->addOrderedQty($from, $to, true)
->addAttributeToFilter('sku', $sku)
->setOrder('ordered_qty', 'desc')
->getFirstItem();
And I am not sure if there is any way to "join" with this reports/product_collection or if there is any way to recreate its "addOrderedQty" data?
This is on Magento 1.7. I can provide further details as needed. I am a beginner with Magento development so any help at all (including resources to learn) would be greatly appreciated. Thanks!
1) Admin Area does have the store ID = 0, so yes this will always be returned.
this will also mean your conditional always fails and never does any joining, it will just try and add the qty_sold to the collection, which of course will not work as it's not part of that entities data.
The issue is the joinAttribute method will only work on "Entites" (it depends on the classes used by the models you are trying to join), and as the reports/product collection isn't one of these you will have to join another way using methods like this:
join() or joinLeft()
with this kind of thing:
$collection->getSelect()
->join(
'customer_entity',
'main_table.customer_id = customer_entity.entity_id',
array('customer_name' => 'email')
);
Was also dealing with this issue and solved it as follows:
protected function _prepareCollection() {
// [...]
$collection = Mage::getModel('catalog/product')->getCollection();
// Add subquery join to sales_flat_order_item to get a SUM of how many times this product has been ordered
$totalOrderedQuery = Mage::getSingleton('core/resource')->getConnection('core_read')
->select()
->from('sales_flat_order_item', array('product_id', 'qty_ordered' => 'SUM(`qty_ordered`)'))
->group('product_id');
$collection->joinField('qty_ordered', $totalOrderedQuery, 'qty_ordered', 'product_id=entity_id', null, 'left');
// [...]
return parent::_prepareCollection();
}
Note the usage of $collection->joinField(), tried using the mentioned $collection->getSelect()->join(), but it gives all sorts of issues with sort orders and filtering due to the internal Magento data collection not recognizing the column as part of the data set.
Then in _prepareColumns you can simply add the column:
$this->addColumn('qty_ordered', array(
'header' => Mage::helper('xyz')->__('Total quantity ordered'),
'sortable' => true,
'width' => '10%',
'index' => 'qty_ordered',
));
You might want to add a renderer which checks and converts a NULL value to '0', otherwise you will end up with empty columns if the product hasn't been ordered yet (you could also fix this in the SELECT query by using IFNULL for qty_ordered).
I was able to achieve what I needed (though it is hardly perfect) thanks to that tip from Andrew. Here is my updated code for setCollection:
public function setCollection($collection)
{
/* #var $collection Mage_Catalog_Model_Resource_Product_Collection */
$store = $this->_getStore();
$collection->getSelect()->joinLeft(
array('oi' => 'sales_flat_order_item'),
'e.entity_id = oi.product_id',
array("qty_sold" => 'SUM(oi.qty_ordered)')
)->group('e.entity_id');
parent::setCollection($collection);
}
I was curious if any Magento developers see a serious flaw in this approach (I'm aware of some of the business logic such as not counting products that were canceled, etc) or recommendations for a better approach. Either way this is "good enough" for now and meets my needs, so I'll post in case others need it.
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?
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
);
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;
Without directly querying the Magento database. How can i remove all the tier prices for a certain product based on quantity and customer group?
Then add new tier prices for this product.
Example:
Remove all tier prices for a product with the SKU: FD001
where the customer group id is: 4
PHP 5.3
Magento 1.4.2
You first have to unset the tier prices and save the product, then add the tier price(s) and save again.
Mage::getModel("catalog/product")->load(123)
->unsTierPrice()
->save()
->setTierPrice(array(
array(
'website_id' => 0,
'all_groups' => 0,
'cust_group' => 4,
'price' => 99.99,
'price_qty' => 1
),
array() // another tier, etc
))
->save();
I ended up solving this by using direct database queries.
As always I'm looking for a better answer.
My Hacky solution:
$product = Mage::getModel('catalog/product')->load(9999);
$dbc = Mage::getSingleton('core/resource')->getConnection('core_write');
$dbc->query('DELETE FROM `catalog_product_entity_tier_price` WHERE `entity_id` = ' . intval($product->getId()) . ' AND `customer_group_id` IN(3,4,6,7) AND qty = 1');
$dbc->query(
'INSERT INTO `catalog_product_entity_tier_price` (`entity_id`,`all_groups`,`customer_group_id`,`qty`,`value`,`website_id`)
VALUES ('. intval($product->getId()) . ',0,' . intval($id) . ',1,' . floatval($price) . ',0)'
);
There's an API available for the product tier price.
Alternatively, you can use some PHP code that uses the Magento code to query for a list of products that match those criteria and then adjust each one. Alan Storm has an article about how Model Collections work (they're the type of object that you would use for this).
Basically it would be something like this to delete the products, I'm not sure how you would set the tier prices, but you can a look at the generated phpdoc documentation. I'm selecting every product that matches customer_group 4 and then deletes each product. You'll have to figure out how to filter things out based on the tier price...
<?php
require 'app/Mage.php';
$app = Mage::app('default'); // Mage_Core_Model_App
$store = $app->getStore(); // Mage_Core_Model_Store
$products = Mage::getModel('catalog/product')->getCollection();
// filter out anything that doesnt match the customer group 4
$products->addFieldToFilter('customer_group', '4');
// loop through each product and delete it
for ($products->load() as $product) {
$product->delete();
}
#omouse's answer pointed us to Magento's API for tier prices. [Updated Link for Magento 1.X's Tier Price API] Note: I'm working with Magento 1.9.2.2.
After looking around for the most efficient way to update a product's tier prices (without using direct SQL), I found the API is the fastest way. It's still slow, but it's better than the other methods I found which recommended doing something like:
// Works, but is slow
$product = Mage::getModel('catalog/product')->load($productId);
$product->unsTierPrice();
$product->save();
$product->load();
$product->setTierPrice($tiers);
$product->save();
Better, I made my array of tier arrays into an array of tier objects, and used the API functions to update the product:
// Build the array of tier level objects
foreach ($tierLevels as $tierLevel) {
$tiers[] = (object) array(
'website' => 'all',
'customer_group_id' => 'all',
'qty' => $tierLevel['min_qty'],
'price' => $tierLevel['unit_price']
);
}
// Use the API to do the update
try {
$tierPriceApi = Mage::getSingleton('catalog/product_attribute_tierprice_api_v2');
$tierPriceApi->update($productId, $tiers);
}
catch (Exception $e) {
// Handle the exception
}
I searched a while to find a solution, which is not pure SQL and does not need a product save, because we want to update tier prices for a catalog of 50k products, so saving all of them is surely not a solution.
I think I finally found a good way.
Mage::getResourceSingleton('catalog/product_attribute_backend_tierprice')
->deletePriceData($product->getId());
$newTierPrice['entity_id'] = $product->getId()
$newTierPrice['all_groups'] = 1;
$newTierPrice['customer_group_id'] = 0;
$newTierPrice['qty'] = 42;
$newTierPrice['value'] = 100;
$newTierPrice['website_id'] = 0;
Mage::getResourceSingleton('catalog/product_attribute_backend_tierprice')
->savePriceData(new Varien_Object($newTierPrice));
I am using Magento 1.4.0.1.
I have over 21000 simple products, each entered into a single category.
There are hundreds of categories in my site.
Some products belong in multiple categories.
Is there some way for me to programmatically add products into multiple categories?
In PHP code you can put them into the category while you are importing them.
Say you have a product called $product and a category ID called $category_id
You can set the categories which a product belongs to by doing the following
$categories = array($category_id);
$product->setCategoryIds($categories);
$product->save();
If the product already has categories and you'd like to add one more then you can use getCategoryIds() like this:
$categories = $product->getCategoryIds();
$categories[] = $categoryId;
$product->setCategoryIds($categories);
$product->save();
Or, as mentioned by Joshua Peck in the comments, you can use the category_api model to add or remove a product from a category without affecting it's current category assignments:
Mage::getSingleton('catalog/category_api')
->assignProduct($category->getId(),$product->getId());
Mage::getSingleton('catalog/category_api')
->removeProduct($category->getId(),$product->getId());
I just want to add that you can remove and add with getSingleton category API:
To Remove product from category:
Mage::getSingleton('catalog/category_api')->removeProduct($category->getId(),$product->getId());
To Add Product to Category:
Mage::getSingleton('catalog/category_api')->assignProduct($category->getId(),$product->getId());
This will not overwrite any categories the product is already in
You can write a module (which takes time but potentially quicker at importing your data) or you can put something together with the API (less involving of Magento programming but potentially slower at importing your data).
Your starting point of what-you-know-already, how valuable your time is and how often you will need to run the update should determine your choice.
Here is the Magento API documentation for adding products to categories (see example at foot of page):
http://www.magentocommerce.com/wiki/doc/webservices-api/api/catalog_category
Well I ended up doing this with the API for some reason of laziness. This adds all the visible products into the category with ID 146:
<?php
$client= new SoapClient('http://www.example.com/api/soap/?wsdl', array('trace' => 1, "connection_timeout" => 120));
// Can be added in Magento-Admin -> Web Services with role set to admin
$sess_id= $client->login('apiuser', 'apikey');
// Get the product list through SOAP
$filters = array('visibility' => '4', 'status' => '1');
$all_products=$client->call($sess_id, 'product.list', array($filters));
// Now chuck them into category 146
foreach($all_products as $product)
{ //var_dump($product);
echo $product['sku']."\n";
$doit=$client->call($sess_id, 'category.assignProduct', array('146', $product['sku']));
}
?>
After looking into the Magento API: Magento adds products to categories in the following way:
public function assignProduct($categoryId, $productId, $position = null, $identifierType = null)
{
$category = $this->_initCategory($categoryId);
$positions = $category->getProductsPosition();
$productId = $this->_getProductId($productId);
$positions[$productId] = $position;
$category->setPostedProducts($positions);
try {
$category->save();
} catch (Mage_Core_Exception $e) {
$this->_fault('data_invalid', $e->getMessage());
}
return true;
}
And getting all the asigned products:
public function assignedProducts($categoryId, $store = null)
{
$category = $this->_initCategory($categoryId);
$storeId = $this->_getStoreId($store);
$collection = $category->setStoreId($storeId)->getProductCollection();
($storeId == 0)? $collection->addOrder('position', 'asc') : $collection->setOrder('position', 'asc');;
$result = array();
foreach ($collection as $product) {
$result[] = array(
'product_id' => $product->getId(),
'type' => $product->getTypeId(),
'set' => $product->getAttributeSetId(),
'sku' => $product->getSku(),
'position' => $product->getPosition()
);
}
return $result;
}
The best above answer points to use Mage::getSingleton('catalog/category_api')
->assignProduct($category->getId(),$product->getId());
Anyway that function is pretty slow in case you have a lot of products/categories to update.
This is because the api function assignProduct():
only accept 1 product/category at time
for every call it loads the product and the category and then save the category
( very slow in case you need to update the same category multiple times )
For example suppose you want to assign 10 products to 1 category ... it gonna load and save the same category 10 times ...
( and load all product that is not actually required if you are sure you product ids are corrects)
A faster way
I came up with the below function that is the same as the api one but it loads and save the category only one time.
This function accept an array as parameter $data that needs to contains all collect changes in the form of $category_id => array(all the products you want to assign)
It is trivial to customize it as for your needs adding, for example, a parameter for store_id ( the function use 0 by default) and position information to the products ...
Add category
function assignCategories($data)
{
foreach ($data as $cat_id => $products_ids) {
/** #var $category Mage_Catalog_Model_Category */
$category = Mage::getModel('catalog/category')
->setStoreId(0)
->load($cat_id );
$positions = $category->getProductsPosition();
foreach ($products_ids as $pid) {
$positions[$pid] = null;
}
$category->setPostedProducts($positions);
$category->save();
}
}
Remove category
function removeProduct($data)
{
foreach ($data as $cat_id => $products_ids) {
/** #var $category Mage_Catalog_Model_Category */
$category = Mage::getModel('catalog/category')
->setStoreId(0)
->load($cat_id);
$positions = $category->getProductsPosition();
foreach ($products_ids as $pid) {
unset($positions[$pid]);
}
$category->setPostedProducts($positions);
$category->save();
}
}
note
Saving the category trigger the Category Flat Data and Catalog URL Rewrites reindex ( if they are set as update on save ).
This is not exactly fast ( the API call does the same ) ...
... so you may want to set these reindex to update manually before running your changes and then do a full reindex on them after
( depending on the number of categories/product you are updating this could be the best option )
We can assign multiple products to the category programmatically using magento scripts. Please create an array of the categories and the select the products based on the custom attribute or field.
$newproducts = $product->getCollection()->addAttributeToFilter(array(array('attribute'=>'attribute_label', 'eq'=> 'attribute_id')));
Loop through the products and assign to category as shown below.
$newCategory = array( $list[0] , $list[$key]);
foreach ($newproducts as $prod)
{
$prod->setCategoryIds(array_merge($prod->getCategoryIds(), $newCategory));
$prod->save();
}
Please refer my tutorial which gives a step by step explanation.
Best way to assign the categories to the products.
Reference from core code - app\code\core\Mage\Catalog\Model\Resource\Category.php
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$categoryProductTable = Mage::getSingleton('core/resource')->getTableName('catalog/category_product');
$productData = array();$position=0;
foreach ($_productCollection as $product) {
$productData[] = array(
'category_id' => (int)$catId1,
'product_id' => (int)$product->getId(),
'position' => (int)$position
);
$productData[] = array(
'category_id' => (int)$catId2,
'product_id' => (int)$product->getId(),
'position' => (int)$position
);
}
$write->insertMultiple($categoryProductTable, $productData);