我正在尝试创建一个自动导入 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();
我在 stackoverflow 的某处读到过
$category->id = Db::getInstance()->Insert_ID();
应该可以解决问题。不幸的是,这总是返回零。有人能看出我做错了什么吗?
编辑:我使用的是 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.
关于php - 在对象上使用 add() 后如何检索插入的 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34785849/