Bearded
Bearded

Reputation: 45

How to render multiple row in a cell in Datatables from a different table?

I am creating a table using datatables and I am having some trouble rendering data in it. My Table structures are.

TABLE_1
|------|------|-------|
|  ID  | NAME | PHONE |
|------|------|-------|
TABLE_2
|------|------------|----------|
|  ID  | TABLE_1_ID | CATEGORY |
|------|------------|----------|

This is my PHP code

$db  = new Database; // Database connection
$sql = "SELECT a.*, b.* FROM TABLE_1 a, TABLE_2 b WHERE a.ID = b.TABLE_1_ID";
$exe = $db->select($sql);
$result = array();
foreach ($exe as $rows) {
    $result[] = $rows;
}
echo json_encode($result);

This is my JavaScript

$('#example').DataTable({
    ajax: {
        url:"data.php",
        dataSrc:""
    },
    columns: [
        {data:"NAME"},
        {data:"CATEGORY"}
    ]
});

Up to this point everything is working fine, the data is perfectly loaded. But the problem is, suppose I have only one row in TABLE_1 and 5 rows in TABLE_2 where TABLE_1.ID = TABLE_2.TABLE_1_ID and bcoz of this my datatable is generating 5 rows but I want all the categories in a single cell and I want only one row instead of 5.

I am thinking of doing some stuff inside the render function, like

$('#example').DataTable({
    ajax: {
        url:"data.php",
        dataSrc:""
    },
    columns: [
        {data:"NAME"},
        {
            data:"ID",
            render: function(data, type, row){
                // Some stuff to render 5 Category in a single cell
                // Using the ID from row.ID (maybe)
                // how to return 5 CATEGORY in this cell
            }
        }
    ]
});

But I really don't know the process and google + stackoverflow + datatables forum is little bit confusing for me bcoz I am not good in Javascript. Can you guys help me achieve this? What type of code or what code I have to write inside the render finction to display 5 CATEGORY in a single cell. Thanks in advance.

Upvotes: 1

Views: 1072

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

You can transform your data in your application layer so that in resultant array you will have only rows for table a along with related category names.

First you need an ordered result set like

select a.id,
  a.phone,
  a.name,
  b.category 
from table_1 a
join table_2 b 
  on a.id = b.table_1_id
order by a.id asc

Then loop through all records and cook your data set

$result = [];
$currentParent = false;
$data = null;
foreach ($rows as $row) {
    /* 
     * if id is changed then its a different record
     * prepare data for new row and create a comma separated string of category names
     */
    if ($currentParent != $row['id']) {
        if($data != null){ // for first and intermediate rows
            $result[]= $data;
        }
        $data = ['name'=> $row['name'], 'category'=> ''];
        $currentParent = $row['id'];
    }
    $data['category'] = empty($data['category']) ? $row['category']: $data['category'] .", ". $row['category'];
}
$result[]= $data; // add data for last row
echo json_encode($result);

The resultant array would look like

Array
(
    [0] => Array
        (
            [name] => item 1
            [category] => Cat 1, Cat 2, Cat3
        )

    [1] => Array
        (
            [name] => item 2
            [category] => Cat 1, Cat 2, Cat3
        )

    [2] => Array
        (
            [name] => item 3
            [category] => Cat 1, Cat 2, Cat3
        )

)

Another shorthand way but not preferred is to apply aggregate methods on query level like if you are using MySQL you can use group_concat but it has a restriction of max character limit (which is adjustable).

Upvotes: 1

Related Questions