Integrity constraint violation for key 'UNQ_CATALOG_PRODUCT_SUPER_ATTRIBUTE_PRODUCT_ID_ATTRIBUTE_ID' - magento

I am creating simple products and then configurable product followed by associating simple products with configurable product. When I run the code for the first time, it works smoothly creating all simple products, configurable product and also an association. But, when I run that code again it says constraint violation. The ID that shows duplicated is the same product ID that was created the last time, when all process were ok.
My code is the following one.
$product_collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*');
$toinsertId = $product_collection->getLastItem()->getId() + 1;
$configurable_attribute = "art_print_sizes";
$attr_id = 133;
$simpleProducts = array();
$lowestPrice = 999999;
$attributes = Mage::getModel('catalogsearch/advanced')->getAttributes();
$attributeArray = array();
foreach ($attributes as $a) {
if ($a->getAttributeCode() == 'art_print_sizes') {
$count = 0;
foreach ($a->getSource()->getAllOptions(false) as $option) {
$option_id = $this->getOptionId("art_print_sizes", $option['label']);
$sku = 'SK_' . '500' . '_' . strval($count);
$sProduct = Mage::getModel('catalog/product');
$sProduct
->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE)
->setWebsiteIds(array(1))
->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE)
->setTaxClassId(5)
->setAttributeSetId(9)
->setSku($sku)
// $main_product_data is an array created as part of a wider foreach loop, which this code is inside of
->setName($wholedata['name'] . " - " . $option['label'])
->setShortDescription($wholedata['short_description'])
->setDescription($wholedata['description'])
->setPrice(sprintf("%0.2f", $wholedata['attr_val'][$count]))
->setData($configurable_attribute, $option_id);
$sProduct->save();
array_push(
$simpleProducts,
array(
"id" => $sProduct->getId(),
"price" => $sProduct->getPrice(),
"attr_code" => 'art_print_sizes',
"attr_id" => $attr_id,
"value" => $option_id,
"label" => $option['label']
)
);
$count++;
}
}
}
$cProduct = Mage::getModel('catalog/product');
$productData = array(
'name' => 'Main configurable Tshirt',
'sku' => 'tshirt_sku',
'description' => 'Clear description about your Tshirt that explains its features',
'short_description' => 'One liner',
'weight' => 1,
'status' => '1',
'visibility' => '4',
'attribute_set_id' => 9,
'type_id' => 'configurable',
'price' => 1200,
'tax_class_id' => 0
);
foreach ($productData as $key => $value) {
$cProduct->setData($key, $value);
}
$cProduct->setStockData(
array(
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => 0,
'use_config_manage_stock' => 0
)
);
$cProductTypeInstance = $cProduct->getTypeInstance();
$attribute_ids = array(133);
$cProductTypeInstance->setUsedProductAttributeIds($attribute_ids);
$attributes_array = $cProductTypeInstance->getConfigurableAttributesAsArray();
foreach ($attributes_array as $key => $attribute_array) {
$attributes_array[$key]['use_default'] = 1;
$attributes_array[$key]['position'] = 0;
if (isset($attribute_array['frontend_label'])) {
$attributes_array[$key]['label'] = $attribute_array['frontend_label'];
} else {
$attributes_array[$key]['label'] = $attribute_array['attribute_code'];
}
}
$cProduct->setConfigurableAttributesData($attributes_array);
$dataArray = array();
foreach ($simpleProducts as $simpleArray) {
$dataArray[$simpleArray['id']] = array();
foreach ($attributes_array as $key => $attrArray) {
array_push(
$dataArray[$simpleArray['id']],
array(
"attribute_id" => $simpleArray['attr_id'][$key],
"label" => $simpleArray['label'][$key],
"is_percent" => 0,
"pricing_value" => $simpleArray['pricing_value'][$key]
)
);
}
}
$cProduct->setConfigurableProductsData($dataArray);
$cProduct->setCanSaveConfigurableAttributes(true);
$cProduct->setCanSaveCustomOptions(true);
$cProduct->save();
The Error is like this
Product ID 126 is already added in database in previous session. And previous session went well adding all necessary products.

Magento will not allow you to update configurable products. So for resolve it just add below code
if($productId){
$resource = Mage::getSingleton('core/resource');
$write = $resource->getConnection('core_write');
$table = $resource->getTableName('catalog/product_super_attribute');
$write->delete($table,"product_id = " . $productId);
}
before
$cProduct->setConfigurableAttributesData($attributes_array);
So your final code will be
if($productId){
$resource = Mage::getSingleton('core/resource');
$write = $resource->getConnection('core_write');
$table = $resource->getTableName('catalog/product_super_attribute');
$write->delete($table,"product_id = " . $productId);
}
$cProduct->setConfigurableAttributesData($attributes_array);
Note: Change $productId variable according to your code. You have to pass product id here.

Related

Error updating data of 1 column by id in Codeigniter 3 database

I am posting the hosting order and I want to increase the "number of sales" column in my "hostings" table, but the data of all packages in my hostings table is increasing.
Here is my relevant code, I can say that there is no method I haven't tried.
$hostingdata = $this->db->query("select number_of_sales from hostings where id=" . $this->input->post('package_id'))->row();
$quantity = 1;
$new_number_of_sales = $hostingdata->number_of_sales + $quantity;
$data = array(
'number_of_sales' => $new_number_of_sales
);
$this->db->update('hostings', $data);
//FULL CODE
public function buy_hosting_post()
{
if ($this->input->post('package_id') && $this->session->userdata('id')) {
$hosting = $this->db->from('hostings')->where('id', $this->input->post('package_id'))->get()->row_array();
if ($hosting) {
$data = array(
'user_id' => $this->session->userdata('id'),
'domain' => $this->input->post('domain'),
'price' => $this->input->post('price'),
// 'end_date' => date('Y-m-d h:i:s',$end_date),
'package_id' => $hosting['id'],
'package_title' => $hosting['name'],
'payment_status' => 0,
);
$this->db->insert('hosting_orders', $data);
$hostingdata = $this->db->query("select number_of_sales from hostings where id=" . $this->input->post('package_id'))->row();
$quantity = 1;
$new_number_of_sales = $hostingdata->number_of_sales + $quantity;
$data = array(
'number_of_sales' => $new_number_of_sales
);
$this->db->update('hostings', $data);
$hosting_order_successful = array(
'hosting_order_successful' => 'success',
);
$this->session->set_userdata('hosting_order_successful', $hosting_order_successful);
redirect(("hosting-siparisi-olusturuldu"));
} else {
redirect(base_url());
}
} else {
redirect(base_url());
}
}
I solved the problem in the following way, but it makes the system heavy.
$hostingdata = $this->db->query("select number_of_sales from hostings where id=" . $this->input->post('package_id'))->row();
$quantity = 1;
$new_number_of_sales = $hostingdata->number_of_sales + $quantity;
$data = array(
'number_of_sales' => $new_number_of_sales
);
$this->db->where('id', $this->input->post('package_id')); // added here.
$this->db->update('hostings', $data);

How to add months dynamically which is stored in database as a header in excel file while exporting using laravel?

Suppose I have items in database which is stored from an Excel file. All the items should be below the header of the months. I have also stored months from the file in the database. So, I want those months to be the header of those items and it's related records. In simple words, I want the header to be dynamic. This is what I have done.
I have tried many code scripts but nothing works. Like Laravel, Excel etc. Can anyone suggest me a good approach?
public function test(){
$data = Item::where('category_id',7)->get()->toArray();
$data2 = month::all();
$itemsArray[] = ['Category Id','Item Name','Created At','Updated At'];
foreach ($data as $value) {
// dd($value);
$itemsArray[] = array(
'Category Id' => $value['category_id'],
'Item Name' => $value['name'],
'Created At' => $value['created_at'],
'Updated At' => $value['updated_at'],
);
}
// Generate and return the spreadsheet
Excel::create('Items', function($excel) use ($itemsArray) {
// Set the spreadsheet title, creator, and description
$excel->setTitle('Items');
// Build the spreadsheet, passing in the items array
$excel->sheet('Items', function($sheet) use ($itemsArray) {
$cellRange = 'A1:D1';
// $spreadsheet->getActiveSheet()->getStyle('A1:D4')
// ->getAlignment()->setWrapText(true);
$sheet->getStyle($cellRange)->getFont()->setBold( true );
$sheet->getStyle($cellRange)->getFont()->setSize( '15' );
$sheet->setBorder($cellRange, 'thick' );
$sheet->getStyle($cellRange)->applyFromArray(array(
'fill' => array(
// 'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'A5D9FF')
)
));
$sheet->fromArray($itemsArray, null, 'A1', false, false);
});
$excel->setCreator('Laravel')->setCompany('Dev505');
$excel->setDescription('Items file');
})->download('xlsx');
}
I need help for getting the actual result.
Akhtar i suggest use to kindly install the Carbon package
https://carbon.nesbot.com/docs/
Try by updating the below code.
$data = Item::where('category_id',7)->get(); // removed toArray()
$data2 = month::all();
$itemsArray[] = ['Category Id','Item Name','Created At','Updated At'];
foreach ($data as $key=>$value) {
$itemsArray[] = array(
'month' => Carbon::now()->addMonth($key)->format('m-Y');
'Category Id' => $value['category_id'],
'Item Name' => $value['name'],
'Created At' => $value['created_at'],
'Updated At' => $value['updated_at'],
);
}
This is the actual code which I have used for excel file. I have solved my problem. Thanks and yeah I am posting this code, if anyone can get help from it.
public function export(){
$data = Category::all();
foreach ($data as $value) {
$value['items'] = Item::where('category_id',$value['id'])->get();
foreach ($value['items'] as $vl) {
$vl['record'] = Record::where('item_id',$vl['id'])->get();
}
}
$data2 = month::pluck('id','month');
foreach ($data2 as $key => $value) {
$m[] = $key;
}
array_unshift($m, 'Categories'); //Insert new element at the start of array
array_push($m, 'Total');
$itemsArray[] = $m;
foreach ($data as $value) {
$itemsArray[] = array(
$itemsArray[0][0] => $value['name'],
// $itemsArray[0][13] => 'Total',
);
foreach ($value['items'] as $val) {
$records_array = [];
$i = 0;
foreach ($val['record'] as $val5) {
$recordval = $val5['value'];
$records_array[$i] = $val5['value'];
$i++;
}
$itemsArray[] = array(
$itemsArray[0][0] => $val['name'],
$itemsArray[0][1] => $records_array[0],
$itemsArray[0][2] => $records_array[1],
$itemsArray[0][3] => $records_array[2],
$itemsArray[0][4] => $records_array[3],
$itemsArray[0][5] => $records_array[4],
$itemsArray[0][6] => $records_array[5],
$itemsArray[0][7] => $records_array[6],
$itemsArray[0][8] => $records_array[7],
$itemsArray[0][9] => $records_array[8],
$itemsArray[0][10] => $records_array[9],
$itemsArray[0][11] => $records_array[10],
$itemsArray[0][12] => $records_array[11],
// $itemsArray[0][13] => 'Total',
);
}
}
// Generate and return the spreadsheet
Excel::create('Items', function($excel) use ($itemsArray) {
// Set the spreadsheet title, creator, and description
$excel->setTitle('Items');
// Build the spreadsheet, passing in the items array
$excel->sheet('Items', function($sheet) use ($itemsArray) {
$cellRange = 'A1:M1';
$sheet->getStyle($cellRange)->getFont()->setBold( true );
$sheet->getStyle($cellRange)->getFont()->setSize( '12' );
$sheet->setBorder($cellRange, 'thin' );
$sheet->getStyle($cellRange)->applyFromArray(array(
'fill' => array(
// 'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'A5D9FF')
)
));
$sheet->fromArray($itemsArray, null, 'A1', false, false);
});
$excel->setCreator('Laravel')->setCompany('Dev505');
$excel->setDescription('Items file');
})->download('xlsx');
}

Magento sort regions by default_name

I need to sort region drop down in one page checkout page. I found data coming from 'Mage_Directory_Helper_Data' I need to sort this data. I tried by adding below code:
$collection = Mage::getModel('directory/region')->getResourceCollection()
->addCountryFilter($countryIds)
->addOrder('default_name', 'DESC')
->load();
But it did not work. Can anyone please help me. Thank You.
Try
if (empty($json)) {
$countryIds = array();
foreach ($this->getCountryCollection() as $country) {
$countryIds[] = $country->getCountryId();
}
$collection = Mage::getModel('directory/region')->getResourceCollection()
->addCountryFilter($countryIds)
->setOrder('default_name','DESC')
->load();
$regions = array(
'config' => array(
'show_all_regions' => $this->getShowNonRequiredState(),
'regions_required' => $this->getCountriesWithStatesRequired()
)
);
foreach ($collection as $region) {
if (!$region->getRegionId()) {
continue;
}
$regions[$region->getCountryId()][$region->getRegionId()] = array(
'code' => $region->getCode(),
'name' => $this->__($region->getName())
);
}
krsort($regions); // or ksort($regions)
$json = Mage::helper('core')->jsonEncode($regions);
}

Filter Orders based on product_id or user_id(Vendor)

I have followed How to create a custom grid from scratch to create custom Sales Orders. Admin is creating vendors and vendors will be uploading product. I want to restrict vendors such that they can see orders placed on their own product only.
There is one new model jbmarketplace/jbmarketplaceproducts in which vendors user_id and product_id is being stored when vendor creates product. But when I'm filtering it gives SQLSTATE[42S22]: Column not found: 1054 Unknown column 'product_id' in 'where clause'. But product_id is available in sales_flat_order_item table.
This problem is Fixed. Updated Code
protected function _prepareCollection()
{
// Get current logged in user
$current_user = Mage::getSingleton( 'admin/session' )->getUser();
// Limit only for vendors
if ( $current_user->getRole()->getRoleId() == Mage::getStoreConfig( 'jbmarketplace/jbmarketplace/vendors_role' ) ) {
// echo( $current_user->getUserId());
$my_products = Mage::getModel( 'jbmarketplace/jbmarketplaceproducts' )
->getCollection()
->addFieldToSelect( 'product_id' )
->addFieldToFilter( 'user_id', $current_user->getUserId() )
->load();
$my_product_array = array();
foreach ( $my_products as $product ) {
$my_product_array[] = $product->getProductId();
$entity = Mage::getModel('sales/order_item')
->getCollection()
->addFieldToSelect('order_id')
->addFieldToFilter('product_id',$my_product_array)
->load();
// echo $entity->getSelect();// will print sql query
}
$d=$entity->getData();
if($d){
$collection = Mage::getResourceModel('sales/order_collection')
// My code
->addFieldToFilter('entity_id', $d)
->join(array('a' => 'sales/order_address'), 'main_table.entity_id = a.parent_id AND a.address_type != \'billing\'', array(
'city' => 'city',
'country_id' => 'country_id'
))
// ->join(Mage::getConfig()->getTablePrefix().'catalog_product_entity_varchar', 'main_table.products_id ='.Mage::getConfig()->getTablePrefix().'catalog_product_entity_varchar.entity_id',array('value'))
->join(array('c' => 'customer/customer_group'), 'main_table.customer_group_id = c.customer_group_id', array(
'customer_group_code' => 'customer_group_code'
))
->addExpressionFieldToSelect(
'fullname',
'CONCAT({{customer_firstname}}, \' \', {{customer_lastname}})',
array('customer_firstname' => 'main_table.customer_firstname', 'customer_lastname' => 'main_table.customer_lastname'))
->addExpressionFieldToSelect(
'products',
'(SELECT GROUP_CONCAT(\' \', x.name)
FROM sales_flat_order_item x
WHERE {{entity_id}} = x.order_id
AND x.product_type != \'configurable\')',
array('entity_id' => 'main_table.entity_id')
)
;
parent::_prepareCollection();
$this->setCollection($collection);
return $this;
}
else
{
echo("Current there are no purchases on your product. Thank you");
}
}
else{
echo("Please Login as Vendor and you will see orders on your products.<br>");
// $current_user = Mage::getSingleton( 'admin/session' )->getUser()->getUserId();
// echo($current_user);
}
}
Here is the code which worked for me.
protected function _prepareCollection()
{
// Get current logged in user
$current_user = Mage::getSingleton( 'admin/session' )->getUser();
// Limit only for vendors
if ( $current_user->getRole()->getRoleId() == Mage::getStoreConfig( 'jbmarketplace/jbmarketplace/vendors_role' ) ) {
// echo( $current_user->getUserId());
$my_products = Mage::getModel( 'jbmarketplace/jbmarketplaceproducts' )
->getCollection()
->addFieldToSelect( 'product_id' )
->addFieldToFilter( 'user_id', $current_user->getUserId() )
->load();
$my_product_array = array();
foreach ( $my_products as $product ) {
$my_product_array[] = $product->getProductId();
$entity = Mage::getModel('sales/order_item')
->getCollection()
->addFieldToSelect('order_id')
->addFieldToFilter('product_id',$my_product_array)
->load();
// echo $entity->getSelect();// will print sql query
}
$d=$entity->getData();
if($d){
$collection = Mage::getResourceModel('sales/order_collection')
// My code
->addFieldToFilter('entity_id', $d)
->join(array('a' => 'sales/order_address'), 'main_table.entity_id = a.parent_id AND a.address_type != \'billing\'', array(
'city' => 'city',
'country_id' => 'country_id'
))
// ->join(Mage::getConfig()->getTablePrefix().'catalog_product_entity_varchar', 'main_table.products_id ='.Mage::getConfig()->getTablePrefix().'catalog_product_entity_varchar.entity_id',array('value'))
->join(array('c' => 'customer/customer_group'), 'main_table.customer_group_id = c.customer_group_id', array(
'customer_group_code' => 'customer_group_code'
))
->addExpressionFieldToSelect(
'fullname',
'CONCAT({{customer_firstname}}, \' \', {{customer_lastname}})',
array('customer_firstname' => 'main_table.customer_firstname', 'customer_lastname' => 'main_table.customer_lastname'))
->addExpressionFieldToSelect(
'products',
'(SELECT GROUP_CONCAT(\' \', x.name)
FROM sales_flat_order_item x
WHERE {{entity_id}} = x.order_id
AND x.product_type != \'configurable\')',
array('entity_id' => 'main_table.entity_id')
)
;
parent::_prepareCollection();
$this->setCollection($collection);
return $this;
}
else
{
echo("Current there are no purchases on your product. Thank you");
}
}
else{
echo("Please Login as Vendor and you will see orders on your products.<br>");
// $current_user = Mage::getSingleton( 'admin/session' )->getUser()->getUserId();
// echo($current_user);
}
}

In Magento Admin: How to add "Color" attribute coloumn under "Products in Cart" Report

In Magento Admin: Under Reports/Shopping Cart/Products in Cart.
I would like to add "Color" attribute column under "Products in Cart" grid. Assuming all products in webshop are configurable products.
i.e; If from Webshop - Customer selects Test Product(configurable product) with Color "Red" option, then this attribute value should be displayed in the report.
Please suggest the best possible way to achieve this!
copy \app\code\core\Mage\Reports\Model\Resource\Quote\Collection.php and paste in app\code\local\Mage\Reports\Model\Resource\Quote\Collection.php
Override public function prepareForProductsInCarts() function
public function prepareForProductsInCarts()
{
$productEntity = Mage::getResourceSingleton('catalog/product_collection');
$productAttrName = $productEntity->getAttribute('name');
$productAttrNameId = (int) $productAttrName->getAttributeId();
$productAttrNameTable = $productAttrName->getBackend()->getTable();
$productAttrPrice = $productEntity->getAttribute('price');
$productAttrPriceId = (int) $productAttrPrice->getAttributeId();
$productAttrPriceTable = $productAttrPrice->getBackend()->getTable();
$ordersSubSelect = clone $this->getSelect();
$ordersSubSelect->reset()
->from(
array('oi' => $this->getTable('sales/order_item')),
array(
'orders' => new Zend_Db_Expr('COUNT(1)'),
'product_id'))
->group('oi.product_id');
$this->getSelect()
->useStraightJoin(true)
->reset(Zend_Db_Select::COLUMNS)
->joinInner(
array('quote_items' => $this->getTable('sales/quote_item')),
'quote_items.quote_id = main_table.entity_id',
null)
->joinInner(
array('e' => $this->getTable('catalog/product')),
'e.entity_id = quote_items.product_id',
null)
->joinInner(
array('product_name' => $productAttrNameTable),
"product_name.entity_id = e.entity_id AND product_name.attribute_id = {$productAttrNameId}",
array('name'=>'product_name.value'))
->joinInner(
array('product_price' => $productAttrPriceTable),
"product_price.entity_id = e.entity_id AND product_price.attribute_id = {$productAttrPriceId}",
array('price' => new Zend_Db_Expr('product_price.value * main_table.base_to_global_rate')))
->joinLeft(
array('order_items' => new Zend_Db_Expr(sprintf('(%s)', $ordersSubSelect))),
'order_items.product_id = e.entity_id',
array()
)
->columns('e.*')
->columns(array('carts' => new Zend_Db_Expr('COUNT(quote_items.item_id)')))
->columns('order_items.orders')
->where('main_table.is_active = ?', 1)
->group('quote_items.product_id');
return $this;
}
And replace with below function.
public function prepareForProductsInCarts()
{
$productEntity = Mage::getResourceSingleton('catalog/product_collection');
$productAttrName = $productEntity->getAttribute('name');
$productAttrNameId = (int) $productAttrName->getAttributeId();
$productAttrNameTable = $productAttrName->getBackend()->getTable();
$productAttrPrice = $productEntity->getAttribute('price');
$productAttrPriceId = (int) $productAttrPrice->getAttributeId();
$productAttrPriceTable = $productAttrPrice->getBackend()->getTable();
$ordersSubSelect = clone $this->getSelect();
$ordersSubSelect->reset()
->from(
array('oi' => $this->getTable('sales/order_item')),
array(
'orders' => new Zend_Db_Expr('COUNT(1)'),
'product_id'))
->group('oi.product_id');
$this->getSelect()
->useStraightJoin(true)
->reset(Zend_Db_Select::COLUMNS)
->joinInner(
array('quote_items' => $this->getTable('sales/quote_item')),
'quote_items.quote_id = main_table.entity_id',
null)
->joinInner(
array('e' => $this->getTable('catalog/product')),
'e.entity_id = quote_items.product_id',
null)
->joinInner(
array('product_name' => $productAttrNameTable),
"product_name.entity_id = e.entity_id AND product_name.attribute_id = {$productAttrNameId}",
array('name'=>'product_name.value'))
->joinInner(
array('product_price' => $productAttrPriceTable),
"product_price.entity_id = e.entity_id AND product_price.attribute_id = {$productAttrPriceId}",
array('price' => new Zend_Db_Expr('product_price.value * main_table.base_to_global_rate')))
### Newly added script ###
->joinLeft(
array('cpei' => 'catalog_product_entity_int'),
'cpei.entity_id = e.entity_id AND cpei.attribute_id = 92',
array()
)
->joinLeft(
array('eaov' => 'eav_attribute_option_value'),
'eaov.option_id = cpei.value',
array('color'=>'eaov.value')
)
### End script ###
->joinLeft(
array('order_items' => new Zend_Db_Expr(sprintf('(%s)', $ordersSubSelect))),
'order_items.product_id = e.entity_id',
array()
)
->columns('e.*')
->columns(array('carts' => new Zend_Db_Expr('COUNT(quote_items.item_id)')))
->columns('order_items.orders')
->where('main_table.is_active = ?', 1)
->group('quote_items.product_id');
return $this;
}
Here cpei.attribute_id = 92 is my "color" attribute id. You can change as per your requirement.
Also put below code in
\app\code\core\Mage\Adminhtml\Block\Report\Shopcart\Product\grid.php file.
$this->addColumn('color', array(
'header' =>Mage::helper('reports')->__('Color'),
'index' =>'color',
Yes we can copy grid.php file from core to local folder.
Works and tested in magento 1.7

Resources