How to test if a category already exists? PrestaSh

2019-08-24 10:22发布

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();

        }
    }

2条回答
SAY GOODBYE
2楼-- · 2019-08-24 11:09

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.

查看更多
Lonely孤独者°
3楼-- · 2019-08-24 11:13

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

查看更多
登录 后发表回答