Добавление поддержки GROUP BY в класс ssp в сложной функции - PullRequest
0 голосов
/ 09 сентября 2018

Я использую datatables v 1.10.19. Как я использовал следующее, группа уничтожает нумерацию страниц и показывает только одну страницу.

        $where = "recipient='".$recipient."' AND grouped='' GROUP BY id DESC";
        echo json_encode(
            SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns, null, $where )
        );  

вот сложная функция для этого:

static function complex ( $request, $conn, $table, $primaryKey, $columns, $whereResult=null, $whereAll=null )
{
    $bindings = array();
    $db = self::db( $conn );
    $localWhereResult = array();
    $localWhereAll = array();
    $whereAllSql = '';

    // Build the SQL query string from the request
    $limit = self::limit( $request, $columns );
    $order = self::order( $request, $columns );
    $where = self::filter( $request, $columns, $bindings );

    $whereResult = self::_flatten( $whereResult );
    $whereAll = self::_flatten( $whereAll );

    if ( $whereResult ) {
        $where = $where ?
            $where .' AND '.$whereResult :
            'WHERE '.$whereResult;
    }

    if ( $whereAll ) {
        $where = $where ?
            $where .' AND '.$whereAll :
            'WHERE '.$whereAll;

        $whereAllSql = 'WHERE '.$whereAll;
    }

    // Main query to actually get the data
    $data = self::sql_exec( $db, $bindings,
        "SELECT `".implode("`, `", self::pluck($columns, 'db'))."`
         FROM `$table`
         $where
         $order
         $limit "
    );

    // Data set length after filtering
    $resFilterLength = self::sql_exec( $db, $bindings,
        "SELECT COUNT(`{$primaryKey}`)
         FROM   `$table`
         $where"
    );
    if(empty($resFilterLength)){$recordsFiltered="['1','2']";}else{
    $recordsFiltered = $resFilterLength[0][0];
    }       
    //$recordsFiltered = $resFilterLength[0][0];

    // Total data set length
    $resTotalLength = self::sql_exec( $db, $bindings,
        "SELECT COUNT(`{$primaryKey}`)
         FROM   `$table` ".
        $whereAllSql
    );
    if(empty($resTotalLength)){$recordsTotal="['1','2']";}else{
    $recordsTotal = $resTotalLength[0][0];
    }           
    //$recordsTotal = $resTotalLength[0][0];

    /*
     * Output
     */
    return array(
        "draw"            => isset ( $request['draw'] ) ?
            intval( $request['draw'] ) :
            0,
        "recordsTotal"    => intval( $recordsTotal ),
        "recordsFiltered" => intval( $recordsFiltered ),
        "data"            => self::data_output( $columns, $data )
    );
}

Вопрос в том, что нужно добавить / изменить, чтобы добавить поддержку в предложение GROUP BY. Однако я могу использовать следующее свойство datatables, чтобы оно показывало GROUP BY DESC, но было бы лучше, если бы оно было на стороне сервера:

'order': [4, 'desc'],

UPDATE:

Как предложено @scaisEdge:

Для 1-го предложения я изменил следующее:

    // Data set length after filtering
    $resFilterLength = self::sql_exec( $db, $bindings,
        "SELECT COUNT(`{$primaryKey}`)
         FROM   `$table`
         $where"
    );

TO

    // Data set length after filtering
    $resFilterLength = self::sql_exec( $db, $bindings,
        "SELECT COUNT(`{$primaryKey}`)
         FROM   `$table`".
         $where
    );

Для 2-го предложения:

удалил предложение GROUP BY из оператора ssp :: complex json encode и

    // Main query to actually get the data
    $data = self::sql_exec( $db, $bindings,
        "SELECT `".implode("`, `", self::pluck($columns, 'db'))."`
         FROM `$table`
         $where
         $order
         $limit "
    );

К

// Main query to actually get the data
$data = self::sql_exec( $db, $bindings,
    "SELECT `".implode("`, `", self::pluck($columns, 'db'))."`
     FROM `$table`
     $where GROUP BY id DESC
     $order
     $limit "
);

отлично работает:)

Ответы [ 2 ]

0 голосов
/ 09 сентября 2018

После вышеуказанного изменения можно легко передать предложение group by или любое другое предложение через оператор ssp :: complex () следующим образом:

        $where = "recipient='".$recipient."' AND grouped=''";
        $extra ='GROUP BY id DESC';
        echo json_encode(
            SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns, null, $where, $extra )
        );

ИЗМЕНЕНИЕ СЛЕДУЮЩЕГО В КОМПЛЕКСНОЙ ФУНКЦИИ SSP.CLASS.PHP:

static function complex ( $request, $conn, $table, $primaryKey, $columns, $whereResult=null, $whereAll=null)

К

static function complex ( $request, $conn, $table, $primaryKey, $columns, $whereResult=null, $whereAll=null, $extra=null )

И

// Main query to actually get the data
$data = self::sql_exec( $db, $bindings,
    "SELECT `".implode("`, `", self::pluck($columns, 'db'))."`
     FROM `$table`
     $where
     $order
     $limit "
);

К

// Main query to actually get the data
$data = self::sql_exec( $db, $bindings,
    "SELECT `".implode("`, `", self::pluck($columns, 'db'))."`
     FROM `$table`
     $where $extra
     $order
     $limit "
);
0 голосов
/ 09 сентября 2018

два предложения

1) в этом коде вы должны использовать конкатенацию строк для $ where

$resFilterLength = self::sql_exec( $db, $bindings,
    "SELECT COUNT(`{$primaryKey}`)
     FROM   `$table` " .   $where 
);

2) кажется, у вас есть порядок по лимиту и смещение для разбивки на страницы после группировки по (и группировка по ID DESC неверна)

   $where = "recipient='".$recipient."' AND grouped=''  
    GROUP BY id ORDER BY id DESC LIMIT 10 OFFSET 5";
...