X-Cart: shopping cart software

X-Cart forums (https://forum.x-cart.com/index.php)
-   Dev Questions (X-Cart 5) (https://forum.x-cart.com/forumdisplay.php?f=56)
-   -   Show random products from a category (https://forum.x-cart.com/showthread.php?t=75816)

sabinudash 11-17-2017 07:01 AM

Re: Banner System Mod's HTML Banner
 
Would you please kindly guide how the script would look like to call products randomly from a specific category to display on a page?

Thank you in advance for your help.

qualiteam 11-26-2017 09:01 PM

Re: Show random products from a category
 
You can extend your widget from \XLite\View\ItemsList\Product\Customer\Category\AC ategory class - this will allow you to show products from a particular category.

But the random order is not that easy. Yes, you can use "ORDER BY RAND()" by returning "RAND()" as the "order by" parameter in getSortByModeDefault() method. But MySQL is too slow when doing this on more than 100 products. So, you will have to implement some tricks to speed up random queries.

tony_sologubov 11-29-2017 05:04 AM

Re: Show random products from a category
 
@sabinudash,

I have found an example of pulling random entities from a repo here:
https://stackoverflow.com/a/39223980/1632233

I went ahead and tried to apply this to product repo and here is the implementation I came up with:

Code:

<?php
// vim: set ts=4 sw=4 sts=4 et:

namespace XLite\Module\XCExample\ModuleDemo\Model\Repo;

/**
 * The "product" model repository
 */
abstract class Product extends \XLite\Model\Repo\Product implements \XLite\Base\IDecorator
{
    public function getRandomProducts($amount = 7)
    {
        return $this->getRandomProductsNativeQuery($amount)->getResult();
    }

    /**
    * @param int $amount
    * @return ORM\NativeQuery
    */
    public function getRandomProductsNativeQuery($amount = 7)
    {
        # set entity name
        $table = $this->getClassMetadata()
        ->getTableName();

        # create rsm object
        $rsm = new \Doctrine\ORM\Query\ResultSetMapping();
        $rsm->addEntityResult($this->getEntityName(), 'p');
        $rsm->addFieldResult('p', 'product_id', 'product_id');

        # make query
        return $this->getEntityManager()->createNativeQuery("
            SELECT p.product_id FROM {$table} p ORDER BY RAND() LIMIT 0, {$amount}
            ", $rsm);
    }
}


Please, let me know if it works for you.

Tony

voidopolis 08-08-2018 07:48 PM

Re: Show random products from a category
 
Tony (once again - fantastic resources you always provide) So, I'm pretty new to x-cart. I'm learning as fast as I can... I'm clueless in how you go about applying this to the product repo...


All times are GMT -8. The time now is 03:11 AM.

Powered by vBulletin Version 3.5.4
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.