如何强制在类别上使用我的 ID,而不是 prestashop 类别的自动递增。 PrestaShop

How to Force using my ID on category, not the auto-increment of prestashop category. PrestaShop

我想定义自己的类别 ID,例如 (999,2222,3333) 并强制在 PrestaShop 数据库上使用它,但是当我执行它时会 (1,2,3) 我怎样才能强制使用我自己的 id

        foreach ($XMLRSString->Families->Family as $family)
        {   
            $_GET['forceIDs'] = true;

            $category = new Category($family->Code);

            $category->id = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->id_category = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->id_category_default = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->is_root_category = false;

            $category->name = array((int)Configuration::get('PS_LANG_DEFAULT') => $family->Designation);

            $category->id_parent = Configuration::get('PS_HOME_CATEGORY');

            $category->link_rewrite = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->add();

        }

在 PrestaShop 中,如果您想强制特定对象(类别、产品、订单等)的 ID 在数据库插入期间绕过 SQL auto-increment,您可以将 force_id 参数设置为 true。

这是一个适用于类别的极简示例:

$category = new Category();
$category->id = 42;
$category->force_id = true;
$category->is_root_category = false;
$category->name = array((int)Configuration::get('PS_LANG_DEFAULT') => 'Test');
$category->link_rewrite = array((int)Configuration::get('PS_LANG_DEFAULT') =>  'test');
$category->id_parent = Configuration::get('PS_HOME_CATEGORY');
$category->add();

这将适用于所有版本的 PrestaShop,并且可以在 ObjectModel class(所有对象的父 class)中找到:

/** @var bool Enables to define an ID before adding object. */
public $force_id = false;

然后在将对象添加到数据库之前检查它,在同一个 class:

public function add($auto_date = true, $null_values = false)
{
    if (isset($this->id) && !$this->force_id)
        unset($this->id);

    ...

希望对您有所帮助!