Search code examples
phpsqljoomla

Select Random rows using jDataBaseDriver


I am new to JDataBaseDriver... I am using SimplePortfolio item show module.The problem is there is no Randome oder or any ordering control implemented in Back-end. So I decided to edit the PHP code by my self. I found following line related to Selection:

public static function getItems($params) {

    $db = JFactory::getDbo();
    $query = $db->getQuery(true);

    $query->select('a.*, a.id AS spsimpleportfolio_item_id , a.tagids AS spsimpleportfolio_tag_id, a.created AS created_on ')
    ->from($db->quoteName('#__spsimpleportfolio_items', 'a'))
    ->where($db->quoteName('a.published') . ' = 1');
    //has category
    if ($params->get('category_id') != '') {
        $query->where($db->qn('a.catid')." = ".$db->quote( $params->get('category_id') ));
    }
    $query->where($db->quoteName('a.access')." IN (" . implode( ',', JFactory::getUser()->getAuthorisedViewLevels() ) . ")")
   ->order($db->quoteName('a.ordering') . ' ASC')
    ->setLimit($params->get('limit', 6));

    $db->setQuery($query);

AFTER I searched I found I can user ORDER BY NEWID() but ut doesn't work in any syntax that I can imagine I Add this and I faced with Errors. What is the correct edit to top code for returning random ordered rows?


Solution

  • Instead of this line

    ->order($db->quoteName('a.ordering') . ' ASC')
    

    Use this to get items in random order

    ->order('RAND()')
    

    If you want to order by new item id created. It should be

    ->order($db->quoteName('a.id') . ' DESC')