Magento Import - FK Integrity Constraint Violation - magento

I'm progmatically importing products into Magento 1.7.0.2 from an XML feed.
The script has run fine for the best part of a week, but now I'm getting the error shown below when products are saving.
How serious is this error, what can cause it?
I've tried reindexing everything and truncating a bunch of tables, the error seems to persist.
The Error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '51-1' for key 'UNQ_CATALOGINVENTORY_STOCK_ITEM_PRODUCT_ID_STOCK_ID'
Import php (sample):
$sProduct = $this->_productModel;
$sProduct->setTypeId($this->_productTypeSimple)
->setWebsiteIds(array(1))
->setStatus($this->_productStatusDisabled)
->setVisibility($this->_productVisibilityNotVisible)
->setTaxClassId(2) //Taxable Good
->setAttributeSetId(XML_FEED_PRODUCT_ATTRIBUTE_SET)
->setSku($arrayProductData['ProductSKU'])
->setName($arrayProductData['ProductName'])
->setShortDescription($arrayProductData['ProductShortDescription'])
->setDescription($arrayProductData['ProductLongDescription'])
->setPrice(sprintf("%0.2f", $arrayProductData['ProductPrice']))
->setRRP(sprintf("%0.2f", $arrayProductData['ProductPrice']))
->setWeight(0)
->setCategoryIds($arrayProductData['ProductCategories'])
->setUrlKey(str_replace(array(" ","'","&"),"-",$arrayProductData['ProductName']) . "-" . $arrayProductData['ProductSKU']);
$sProduct->setStockData(
array(
'use_config_manage_stock' => 1,
'is_in_stock' =>1,
'qty' => $arrayProductData['ProductStockQty']
)
);
$sProduct->setMetaTitle($arrayProductData['ProductName'])
->setMetaDescription(str_replace("<<THE_PRODUCT>>",$arrayProductData['ProductName'], DEFAULT_META_DESC));
if(isset($arrayProductData['ProductSize'])) {
$sProduct->setData("sizes", $arrayProductData['ProductSize']);
}
if(isset($arrayProductData['ProductColour'])) {
$sProduct->setData("color", $arrayProductData['ProductColour']);
}
try {
$sProduct->save();
}
catch (Mage_Core_Exception $e) {
echo $e->getMessage();
}
Thanks for looking.

As the error show
UNQ_CATALOGINVENTORY_STOCK_ITEM_PRODUCT_ID_STOCK_ID
There is duplicate entry in DB table ( cataloginventory_stock_item ) for the same product_id / stock_id
This could happen for different reasons
You can solve this by setting the ID of the product manually before save so it won't conflict get the last product ID and increment it.
or delete the row related to this new product from the table before save

Further down the script I was creating configurable products based on certain criteria.
For reasons I've not yet uncovered the SKU of this configurable product doesn't appear to be unique, causing the issue above.
Thanks anyway Meabed.

Related

using observers to delete all relations in Laravel

My tables structure is :
Shopsidname
Productsidnameshop_id
Product_tagsidlabelvalueproduct_id
Problem is: I want to delete products and product tags on deleting shop
I made two Observers and registered both :
ShopObserver
ProductObserver
ShopObserver :
public function deleting(Shop $shop)
{
$shop->products()->delete();
}
ProductObserver :
public function deleting(Product $product)
{
$product->tags()->delete();
}
But I have following error :
"SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`tabadolha`.`product_tags`, CONSTRAINT `product_tags_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`)) (SQL: delete from `products` where `products`.`shop_id` = 26 and `products`.`shop_id` is not null)"
I don't want to use nullOnDelete on my database. I want to delete it by observer.
Any way?
The problem is that your second observer of tags should be fired FIRST, and you can't specify the order of observers in Laravel.
What I would to is delete the tags in the same ShopObserver, before deleting the products, and not create a separate ProductObserver.
Something like:
$shop->products->each(function($product) {
$products->tags()->delete();
});
$shop->products()->delete();
Please test, not sure about the syntax, typed it with phone from my memory :)

Filament SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

When I create a new row in the table 'partidos' I get this message:
'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '
That is ok, I know it is a duplicate entry, but I get an error page from Laravel. My question is, how I can get an alert or similar instead of that error page?
I tried to use laravel validation rules, but I don't know how to use them with Filament
Thanks
A QueryException is being thrown due to the duplicate key violation in your partidos table.
You could encapsulate your statement(s) in a try/catch block to catch and handle the exception however you see fit. For example:
try {
// perform your database action here
} catch(\Illuminate\Database\QueryException $ex){
// $ex->getMessage(); will provide a string representation of the error
// from here you can handle the exception and return a response
}
Alternatively, you can use validation, specifically the unique rule to validate any values that must be unique in the database table are in fact unique.
public function action(Request $request)
{
// if validation fails, laravel will redirect back to the page with errors
$request->validate([
'field' => ['required', 'unique:partidos'],
]);
}

Magento dmin Checkboxes Save magento categories to custom database table

I'm currently developing a custom module for Magento and theres one thing I´m not able to get working.
I have a front-end display of employees and an backend so I can add employees.
I save the employees in a regular mysql table(so not EAV). Just to add employees to the database is no problem but now I want to add a different table so that the employees can be part of more than one category. I want to display the magento categories, and that I get working, but next I want to save that value along with the id of my employee in my own table in the database. Thats the problem i'm having.
I've tried using the magento admin grid and have a tab for adding and editing. I´ve tried to add a new tab and adding checkboxes there to check and save but can get it to work
Maybe I'm completely of, if that so youre free to suggest a different approach.
add this to save action
if (isset($data['categories'])) {
$data['categories'] = explode(',', $data['categories']);
if (is_array($data['categories'])) {
$data['categories'] = array_unique($data['categories']);
}
}
and this to collection
$this->getSelect()->join(
array('category_table' => $this->getTable('qbanner/qbanner_category')), 'main_table.qbanner_id = category_table.qbanner_id', array()
)
->where('category_table.category_id = ?', $categoryId);
return $this;
hope this will help you

Update in sales order table - Magento Model

I want to update one field value in magento I am using
$data = array('xxx'=>$xxx);
$orderModel = Mage::getModel('sales/order')->load($orderId)->addData($data);
try {
$orderModel->setId($orderId)->save();
echo "Data updated successfully.";
} catch (Exception $e){
echo $e->getMessage();
}
But it is not working, Any one can suggest me what I am doing the create problem in updating data.
you can do the MAGIC function, get and set function
try directly:
// if your attribute is column named is_active then you can getIsActive() or setIsActive(1)
$orderModel = Mage::getModel('sales/order')->load($orderId)->setYourAttribute($data);
// it means you can set and get column named by ['your_attribute']
try {
$orderModel->setId($orderId)->save();
echo "Data updated successfully.";
} catch (Exception $e){
echo $e->getMessage();
}
hmmm. i don't know why you set the entity_id of sales/order model. but it won't work because the entity_id can be the foreign key on another table, example : sales_flat_order_payment
Your code setId($orderId) looks like you either want to explicitely set an order entity_id (that is, create an order), or you're just not aware of the fact, that you don't need setId($orderId) after loading, if you only want to update the given order.
In case you're trying to create an order: the sales/order model normally does not allow to explicitely set an order's entity_id, because it uses a primary key being auto-incremented by default.
In case you're trying to update an existing order: remove the setId($orderId) from the save() chain.
Second, you need to extend the sales/order model with an xxx attribute first, if you want to be able to save its value to the database.
There are several ways to extend the sales/order model to have a custom attribute. For example you could have your own setup script in your app/code/local/Mycompany/Mymodule/sql/myresource/ folder:
// Mage_Eav_Model_Entity_Setup
$oInstaller = $this;
// Add EAV attribute
$oInstaller->startSetup();
$oInstaller->addAttribute(
'order',
'my_attribute',
array(
'type' => 'int'
)
);
$oInstaller->endSetup();
// Add flat attribute
if (Mage::getVersion() >= 1.1) {
$oInstaller->startSetup();
$oConnection = $oInstaller->getConnection();
$oConnection->addColumn(
$oInstaller->getTable('sales_flat_order'),
'my_attribute',
'TINYINT(1) NOT NULL'
);
$oInstaller->endSetup();
}

Updating price programmatically

I am trying to update several products that are fed from an XML file using:
$productid = Mage::getModel('catalog/product')->getIdBySku($url->product);
echo 'Loaded Product: ' . $url->product;
// Initiate product model
$product = Mage::getModel('catalog/product');
$product->setPrice($url->price);
try
{
$product->save();
echo "Save / Updated"."\r\n";
}
catch (Exception $ex) {
echo "<pre>".$ex."</pre>";
}
The problem I'm getting a SQL error:
exception 'Mage_Eav_Model_Entity_Attribute_Exception' with message 'SQLSTATE[23000]:
Integrity constraint violation: 1062 Duplicate entry '531-0-82-1.0000-0'
The product with the ID of 531 does exist in my db, all I'm wanting to do is update it's price.
What could be causing this?
Try this to update
$product = Mage::getModel('catalog/product');
change to
$product = Mage::getModel('catalog/product')->load($productid);
You have to load a product to update its attributes.
Well it seemed to not like the fact I had tiered prices on that product.
Cleared them, re-indexed, re-created tiered pricing, all seems good

Resources