Datatables 结合列数据和其他表数据的服务器端数据表

Datatables 结合列数据和其他表数据的服务器端数据表,datatables,server-side,Datatables,Server Side,我使用AJAX创建了这个数据表: 我想把它变成服务器端,因为它可以容纳超过10k的条目。这是我使用Datatables文档编写的代码: 服务器端获取数据: <?php /* * DataTables example server-side processing script. * * Please note that this script is intentionally extremely simple to show how * server-side processi

我使用AJAX创建了这个数据表:

我想把它变成服务器端,因为它可以容纳超过10k的条目。这是我使用Datatables文档编写的代码:

服务器端获取数据:

<?php
 
/*
 * DataTables example server-side processing script.
 *
 * Please note that this script is intentionally extremely simple to show how
 * server-side processing can be implemented, and probably shouldn't be used as
 * the basis for a large complex system. It is suitable for simple use cases as
 * for learning.
 *
 * See http://datatables.net/usage/server-side for full details on the server-
 * side processing requirements of DataTables.
 *
 * @license MIT - http://datatables.net/license_mit
 */
 
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Easy set variables
 */
 
// DB table to use
$table = 'library_book';
 
// Table's primary key
$primaryKey = 'id';
 
// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
    array( 'db' => 'title', 'dt' => 0 ),
    array( 'db' => 'subtitle',   'dt' => 1 ),
    array( 'db' => 'isbn',  'dt' => 2 ),
    array( 'db' => 'subject_id',     'dt' => 3 ),
    array( 'db' => 'author_id',     'dt' => 4 ),
    array( 'db' => 'creator_id',     'dt' => 5 ),
    array(
        'db'        => 'creationdate',
        'dt'        => 6,
        'formatter' => function( $d, $row ) {
            return date( 'jS M y', strtotime($d));
        }
    )
);
 
// SQL server connection information
$sql_details = array(
    'user' => 'root',
    'pass' => '',
    'db'   => 'mycbs',
    'host' => 'localhost'
);
 
 
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP
 * server-side, there is no need to edit below this line.
 */
 
require( 'ssp.class.php' );
 
echo json_encode(
    SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);

为了实现我所需要的,我在Datatable序列化脚本和ss books get controller中做了一些更改

数据表序列化:

$(document).ready(function() {
    $('#books').DataTable( {
          dom: "<'row'<'col-md-4'B><'col-md-4'f><'col-md-4'p>>" +
                 "<'row'<'col-md-6'><'col-md-6'>>" +
                 "<'row'<'col-md-12't>><'row'<'col-md-4'l><'col-md-4'i><'col-md-4'p>>",
          buttons: [
               {
                   extend: 'collection',
                   text: '<i class="la la-download"></i> Export',
                   autoClose: true,
                   className: 'btn btn-success btn-icon-sm btn-square dropdown-toggle',
                   buttons: [
                               { text: '<i class="fas fa-copy"></i>\xa0\xa0  Copy', extend: 'copyHtml5'},
                               { text: '<i class="fas fa-file-excel"></i>\xa0\xa0  Excel', extend: 'excelHtml5'},
                               { text: '<i class="fas fa-file-csv"></i>\xa0\xa0  CSV', extend: 'csvHtml5'},
                               { text: '<i class="fas fa-file-pdf"></i>\xa0\xa0  PDF', extend: 'pdfHtml5'},
                               { text: '<i class="fas fa-print"></i>\xa0\xa0  Print', extend: 'print' }
                            ],
                        fade: true,
               }
            ],
          "columnDefs": [
              // Use render to mix the title column and the subtitle column and to add the HTML tags. Also generate de buttons grabbing the ID from the id column of the table.
              {
                  "render": function ( data, type, row ) {
                      if (row[8] == "") {
                          var title = data;
                      } else {
                          var title = data + ' | ' + row[8];
                      }
                      return '<a class="kt-link kt-font-bold" href="./book/'+row[7]+'" >' + title + '</a>';
                  },
                  "targets": 0
              },
              {
                  "render": function ( data, type, row ) {
                      return '<a href="./book/'+row[7]+'" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="View Book"> <i class="fas fa-eye"></i> </a> <a href="./book/'+row[7]+'#add-copy" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="Add Copy"> <i class="fas fa-plus"></i> </a> <a href="./book/'+row[7]+'#edit-book" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="Edit Book"> <i class="fas fa-edit"></i> </a> <a href="./index.php?action=book-del&id='+row[7]+'" id="btn" class="btn btn-sm btn-clean btn-icon btn-icon-md btn-book-del" title="Delete Book"> <i class="fas fa-trash-alt"></i> </a>';
                  },
                  "targets": 6
              },
              // Then hide the subtitle/id columns (which I won't need to show in frontend)
              { "visible": false,  "targets": [ 7 ] },
              { "visible": false,  "targets": [ 8 ] }
          ],
          pageLength: 25,
          responsive: true,
          "processing": true,
          "serverSide": true,
          "ajax": "index.php?action=ss-books-get"
      } );
} );
$(文档).ready(函数(){
$('#books')。数据表({
dom:“+
"" +
"",
按钮:[
{
扩展:'集合',
文本:“导出”,
自动关闭:是的,
类名:“btn btn成功btn图标sm btn方形下拉切换”,
按钮:[
{text:'\xa0\xa0 Copy',扩展:'copyHtml5'},
{text:'\xa0\xa0 Excel',扩展:'excelHtml5'},
{text:'\xa0\xa0 CSV',扩展:'csvHtml5'},
{text:'\xa0\xa0 PDF',扩展名:'pdfHtml5'},
{text:'\xa0\xa0 Print',扩展:'Print'}
],
是的,
}
],
“columnDefs”:[
//使用render混合标题列和副标题列,并添加HTML标记。还可以生成从表的ID列获取ID的de按钮。
{
“渲染”:函数(数据、类型、行){
如果(第[8]行=“”){
var title=数据;
}否则{
变量标题=数据+“|”+行[8];
}
返回“”;
},
“目标”:0
},
{
“渲染”:函数(数据、类型、行){
返回“”;
},
“目标”:6
},
//然后隐藏subtitle/id列(我不需要在前端显示)
{“可见”:false,“目标”:[7]},
{“可见”:false,“目标”:[8]}
],
页长:25,
回答:是的,
“处理”:对,
“服务器端”:正确,
“ajax”:“index.php?action=ss books get”
} );
} );
控制器可获得:

<?php

$table = 'library_book';
 
$primaryKey = 'id';

$columns = array(
    
    array(
        'db'        => 'title',
        'dt'        => 0
    ),
    array( 'db' => 'isbn',  'dt' => 1 ),
    array(
        'db'        => 'subject_id',
        'dt'        => 2,
        'formatter' => function( $d, $row ) {
            return library::getSubjectByID($d);
        }
    ),
    array(
        'db'        => 'id',
        'dt'        => 3,
        'formatter' => function( $d, $row ) {
            return library::getLevelsByBookID($d);
        }
    ),
    array(
        'db'        => 'id',
        'dt'        => 4,
        'formatter' => function( $d, $row ) {
            return library::getCategoriesByBookID($d);
        }
    ),
    array(
        'db'        => 'id',
        'dt'        => 5,
        'formatter' => function( $d, $row ) {
            return library::getCountCopiesByBookID($d);
        }
    ),
    array(
        'db'        => 'type',
        'dt'        => 6
    ),
    array(
        'db'        => 'id',
        'dt'        => 7
    ),
    array(
        'db'        => 'subtitle',
        'dt'        => 8
    ),
);

require( 'ssp.class.php' );
 
echo json_encode(
    SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns, $whereResult=null, $whereAll="hidden = 0 AND type = 1"  )
);

有什么想法吗?我一直在努力,但没有成功
$(document).ready(function() {
    $('#books').DataTable( {
          dom: "<'row'<'col-md-4'B><'col-md-4'f><'col-md-4'p>>" +
                 "<'row'<'col-md-6'><'col-md-6'>>" +
                 "<'row'<'col-md-12't>><'row'<'col-md-4'l><'col-md-4'i><'col-md-4'p>>",
          buttons: [
               {
                   extend: 'collection',
                   text: '<i class="la la-download"></i> Export',
                   autoClose: true,
                   className: 'btn btn-success btn-icon-sm btn-square dropdown-toggle',
                   buttons: [
                               { text: '<i class="fas fa-copy"></i>\xa0\xa0  Copy', extend: 'copyHtml5'},
                               { text: '<i class="fas fa-file-excel"></i>\xa0\xa0  Excel', extend: 'excelHtml5'},
                               { text: '<i class="fas fa-file-csv"></i>\xa0\xa0  CSV', extend: 'csvHtml5'},
                               { text: '<i class="fas fa-file-pdf"></i>\xa0\xa0  PDF', extend: 'pdfHtml5'},
                               { text: '<i class="fas fa-print"></i>\xa0\xa0  Print', extend: 'print' }
                            ],
                        fade: true,
               }
            ],
          "columnDefs": [
              // Use render to mix the title column and the subtitle column and to add the HTML tags. Also generate de buttons grabbing the ID from the id column of the table.
              {
                  "render": function ( data, type, row ) {
                      if (row[8] == "") {
                          var title = data;
                      } else {
                          var title = data + ' | ' + row[8];
                      }
                      return '<a class="kt-link kt-font-bold" href="./book/'+row[7]+'" >' + title + '</a>';
                  },
                  "targets": 0
              },
              {
                  "render": function ( data, type, row ) {
                      return '<a href="./book/'+row[7]+'" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="View Book"> <i class="fas fa-eye"></i> </a> <a href="./book/'+row[7]+'#add-copy" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="Add Copy"> <i class="fas fa-plus"></i> </a> <a href="./book/'+row[7]+'#edit-book" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="Edit Book"> <i class="fas fa-edit"></i> </a> <a href="./index.php?action=book-del&id='+row[7]+'" id="btn" class="btn btn-sm btn-clean btn-icon btn-icon-md btn-book-del" title="Delete Book"> <i class="fas fa-trash-alt"></i> </a>';
                  },
                  "targets": 6
              },
              // Then hide the subtitle/id columns (which I won't need to show in frontend)
              { "visible": false,  "targets": [ 7 ] },
              { "visible": false,  "targets": [ 8 ] }
          ],
          pageLength: 25,
          responsive: true,
          "processing": true,
          "serverSide": true,
          "ajax": "index.php?action=ss-books-get"
      } );
} );
<?php

$table = 'library_book';
 
$primaryKey = 'id';

$columns = array(
    
    array(
        'db'        => 'title',
        'dt'        => 0
    ),
    array( 'db' => 'isbn',  'dt' => 1 ),
    array(
        'db'        => 'subject_id',
        'dt'        => 2,
        'formatter' => function( $d, $row ) {
            return library::getSubjectByID($d);
        }
    ),
    array(
        'db'        => 'id',
        'dt'        => 3,
        'formatter' => function( $d, $row ) {
            return library::getLevelsByBookID($d);
        }
    ),
    array(
        'db'        => 'id',
        'dt'        => 4,
        'formatter' => function( $d, $row ) {
            return library::getCategoriesByBookID($d);
        }
    ),
    array(
        'db'        => 'id',
        'dt'        => 5,
        'formatter' => function( $d, $row ) {
            return library::getCountCopiesByBookID($d);
        }
    ),
    array(
        'db'        => 'type',
        'dt'        => 6
    ),
    array(
        'db'        => 'id',
        'dt'        => 7
    ),
    array(
        'db'        => 'subtitle',
        'dt'        => 8
    ),
);

require( 'ssp.class.php' );
 
echo json_encode(
    SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns, $whereResult=null, $whereAll="hidden = 0 AND type = 1"  )
);
public static function getSubjectByID($id) {
    if ($id == NULL) { $id = 0; } else {}
    $a = new SQLMan();
    $a->tablename = "library_subject";
    $result = $a->select("","",$where="id =".$id);
    if (empty($result)) {
        return '<span class="kt-badge kt-badge--success greysuccess kt-badge--inline kt-badge--pill"> N/A </span>';
    } else {
        $result = $result[0];
        return '<span class="kt-badge kt-badge--success kt-badge--inline kt-badge--pill">'.$result->fields["name"].'</span>';
    }
}
public static function getCategoriesByBookID($id) {
    $final = "";
    $a = new SQLMan();
    $a->tablename = "library_category";
    $categoria= $a->select("","",$where=" hidden = 0");
    $a = "";
    $a = new SQLMan();
    $a->tablename = "library_categoryvsbook";
    $anycat = $a->select("many","","book_id=".$id);
    if (count($anycat)>0) {
        foreach($anycat as $cl) {
            foreach($categoria as $cat) {
                if ($cat->fields["id"] == $cl->fields["category_id"]) {
                    $final .= "<span class='kt-badge kt-badge--success  kt-badge--inline kt-badge--pill'>".$cat->fields["name"]."</span> ";
                    $a = "";
                } else {

                }
            }
        } 
    } else {
        $final .= "<span class='kt-badge kt-badge--success greysuccess kt-badge--inline kt-badge--pill'>N/A</span> ";
        $a = "";
    }
    return $final;
}
public static function getLevelsByBookID($id) {
    $final = "";
    $a = new SQLMan();
    $a->tablename = "library_level";
    $categoria= $a->select("","",$where=" hidden = 0");
    $a = "";
    $a = new SQLMan();
    $a->tablename = "library_levelvsbook";
    $anycat= $a->select("many","","book_id=".$id);
    
    if (count($anycat)>0) {
        foreach($anycat as $cl) {
            foreach($categoria as $cat) {
                if ($cat->fields["id"] == $cl->fields["level_id"]) {
                    $final .= "<span class='kt-badge kt-badge--success  kt-badge--inline kt-badge--pill'>".$cat->fields["name"]."</span> ";
                    $a = "";
                } else {

                }
            }
        } 
    } else {
        $final .= "<span class='kt-badge kt-badge--success greysuccess kt-badge--inline kt-badge--pill'>N/A</span> ";
        $a = "";
    }
    return $final;
}
public static function getCountCopiesByBookID($id) {
    $result = "";
    $a = new SQLMan();
    $a->tablename = "library_copy";
    $ejemplares= $a->select("","",$where=" hidden = 0 AND book_id =".$id);
    
    $count = "0";
    $countb = "0";
    foreach($ejemplares as $ejem) { 
        if ($ejem->fields["status"] == "0") {
            $count++;
        } else {
        }
    }
    $countb = count($ejemplares);
    if ($count>0) { 
        $popcount = "kt-badge--success"; 
    } else { 
        $popcount = "kt-badge--success greysuccessbadge";
    }; 
    $result .= "<span class='kt-badge ".$popcount." kt-badge--dot kt-badge--xl'></span>&nbsp;&nbsp; "; 
    $result .= $count . " / " . $countb; 
    $count = "0"; $countb = "0";
    return $result;
}