How to test if a category already exists? PrestaShop

不问归期 提交于 2019-12-13 04:09:21

问题


I get the category from other database web service and I put them on PrestaShop when I refresh the file to add categories I wanna make sure if the category id exists, if exist I wanna update the category.

$XMLRQString = '<?xml version="1.0" encoding="utf-8"?>'.
    '<x:Winmax4GetFamiliesRQ xmlns:x="urn:Winmax4GetFamiliesRQ">'.
    '</x:Winmax4GetFamiliesRQ >';

$return = $client->GetFamilies($Params);
$XMLRSString = new SimpleXMLElement($return->GetFamiliesResult);
if ($XMLRSString->Code > 0)
    echo '</br>Error: '.$XMLRSString->Code." ".$XMLRSString->Message;
else{

        foreach ($XMLRSString->Families->Family as $family)
        {   

            $category = new Category();

            $category->id = $family->Code;

            $category->force_id = true;

            $category->is_root_category = false;

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

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

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

            $category->add();

        }
    }

回答1:


In general, If you have large data (and also safe data), it's better to insert your data directly to your database. Use Db class instead of Category class.

Otherwise, you must use a save() method instead of add() method




回答2:


This would work:

$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
$home = (int)Configuration::get('PS_HOME_CATEGORY');
$category = new Category((int)$family->Code);
$category->is_root_category = false;
$category->name = array($default_lang => $family->Designation);
$category->link_rewrite = array($default_lang => $family->Code);
$category->id_parent = $home;
$category->save();

Also, you can always check if an object is valid using the Validate::isLoadedObject() static method.



来源:https://stackoverflow.com/questions/56345644/how-to-test-if-a-category-already-exists-prestashop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!