I am trying to create a script that automatically imports a XML file, I got this working, but for a reason I need to get the ID from a category I am adding, this category ID is auto increment, so there is no way I could get this out of the existing data.
So my code looks like this:
$category = new Category;
$category->active = 1;
$category->id_parent = 3;
$category->name[1] = $product->category_name;;
$category->link_rewrite[1] = Tools::link_rewrite($product_xml->category_name);
echo "<br />name of new category = $product->category_name <br /> <br />";
$category->add();
$category->id = Db::getInstance()->Insert_ID();
I have read somewhere here on stackoverflow that
$category->id = Db::getInstance()->Insert_ID();
Should do the trick. Unfortunately, this returns always zero. Can someone see what I did wrong?
Edit: I am using prestashop version 1.6
Edit: Answer: You don't need "Db::getInstance()->Insert_ID();" after $object->add() there is already an ID generated, the only thing you have to do is: echo $object->id; and you'll see your ID.
Best regards,
Evert Arends
Prestashop already did this command in classes/ObjectModel.php
method add()
// Get object id in database
$this->id = Db::getInstance()->Insert_ID();
When you use add()
on an object this object automatically get its new id from database. So $category->id
should already contain its new ID.
$category = new Category;
$category->active = 1;
$category->id_parent = 3;
$category->name[1] = $product->category_name;;
$category->link_rewrite[1] = Tools::link_rewrite($product_xml->category_name);
echo "<br />name of new category = $product->category_name <br /> <br />";
$category->add(); // Add will add the category to database and update category with its new id automatically
echo "category id = ".$category->id; // will show the category id.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With