在对象上使用 add() 后如何检索插入的 ID?

How to retrieve inserted ID after using add() on an Object?

我正在尝试创建一个自动导入 XML 文件的脚本,我成功了,但是出于某种原因,我需要从我添加的类别中获取 ID,这个类别 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();
        $category->id = Db::getInstance()->Insert_ID();

我在 Whosebug 的某处读到

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

应该可以解决问题。不幸的是,这个 returns 总是零。有人能看出我做错了什么吗?

编辑:我使用的是 prestashop 1.6 版

编辑:答案: 你不需要 "Db::getInstance()->Insert_ID();" 在 $object->add() 之后已经生成了一个 ID,你唯一需要做的就是: echo $object->id;然后你会看到你的 ID。

此致,

埃弗阿伦兹

Prestashop 已经在 classes/ObjectModel.php 方法中执行了此命令 add()

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

当您在对象上使用 add() 时,该对象会自动从数据库中获取其新 ID。所以 $category->id 应该已经包含了它的新 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.
Last Inserted Id:

      echo $category->id;