Search code examples
phpapiprestashop

Prestashop webservice, request random row of ressources


I'm developping a webservice on prestashop using the PSWebServiceLibrary with php. That i want is to make request that get random row , for example i want to get 10 random products. On the webservice api there is no option which can make this one; Is there a way to make that request using the PSWebServiceLibrary on php? Like i made below:

 public function get_random_product(){
        $webservice = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
        $opt['resource'] = 'products';
        $opt['filter']['active'] = 1;
        $opt['limit'] = 10;
        $opt['display'] = 'full';
        $xmlResponse = $webservice->get($opt);
        $allproducts = $xmlResponse->children()->children();
        return ($allproducts);
 }

This one just get the 10 first row product but i want that the result is random. Thanks :)


Solution

  • You can get 10 random products from DB with this

    select id_product from ps_product order by rand() limit 10;
    

    And then retrieve from API with, for example

    www.yourapp.com/api/products/?filter[id]=[1|2|3|4|5|6|7|8|9|10]
    

    In your function

    public function get_random_product(){
        $rows = DB::getInstance()->executeS('select id_product from ps_product where active order by rand() limit 10');
        $joinedIdProducts = implode('|', $rows);
        $webservice = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
        $opt['resource'] = 'products';
        $opt['filter']['active'] = 1;
        $opt['filter']['id'] = $joinedIdProducts;
        $opt['limit'] = 10;
        $opt['display'] = 'full';
        $xmlResponse = $webservice->get($opt);
        $allproducts = $xmlResponse->children()->children();
        return ($allproducts);
    

    }