How to get the inserted identifier after using add () in an object?

I am trying to create a script that automatically imports an XML file, I got this working, but for some reason I need to get the identifier from the category that I am adding, this category identifier is an automatic increment, so I can’t get it from 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 read somewhere here about stackoverflow, which

$ category-> id = Db :: getInstance () → Insert_ID ();

Gotta do the trick. Unfortunately, this always returns zero. Can anyone see what I did wrong?

Edit: I am using prestashop version 1.6

: : "Db:: getInstance() → Insert_ID();" $object- > add() , : echo $object- > id; .

,

Evert Arends

+4
2

Prestashop classes/ObjectModel.php add()

// Get object id in database
$this->id = Db::getInstance()->Insert_ID();

add() , . , $category->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.
+5
Last Inserted Id:

      echo $category->id;
0

Source: https://habr.com/ru/post/1624239/


All Articles