我如何设法将group_concat值循环到数据表和复选框

时间:2017-12-13 01:47:10

标签: laravel datatable

我在产品表中存储id_supplier。我能够在表格中只用一行显示每个商品代码及其供应商ID。我也需要供应商的名称,但我在分离ID和名称时面临问题。

//query
select code, group_concat(s.supplier_id,s.supplier_name) AS supplier_id_name
from catalog c
left join product p on p.product_id= c.product_id
left join supplier s on s.supplier_id = p.product_id
group by code;


    //query will show following output

    id supplier - 1,  name - abc
    id supplier - 2, name - def

    Code        | Supplier
    A001        | 1abc,2def  // id and name of supplier

我的期望

Code        | Supplier
A001        | checkboxes value = 1 and then display supplier name beside....... and continue in the same row if  more supplier

代码的每个供应商显示都会有一个复选框,复选框将包含供存储目的的供应商ID。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

有两种解决方案。

解决方案1:仅使用MySQL查询本身编写HTML代码,使用以下sql:

// Query

SELECT CODE, 
       GROUP_CONCAT(CONCAT('<input type="checkbox" value="', s.supplier_id, '"> ', s.supplier_name) SEPARATOR ',') AS supplier_id_names
    FROM catalog c
    LEFT JOIN product p ON p.product_id= c.product_id
    LEFT JOIN supplier s ON s.supplier_id = p.product_id
    GROUP BY CODE;

解决方案2:首先获取供应商ID和名称,用特定的char分隔,然后在后端代码中,通过拆分来过滤每个id和名称,以生成完整的HTML代码:(以下是PHP代码)

$query= "SELECT CODE, 
                GROUP_CONCAT(CONCAT(s.supplier_id, ':', s.supplier_name) SEPARATOR '|||') AS supplier_id_names
    FROM catalog c
    LEFT JOIN product p ON p.product_id= c.product_id
    LEFT JOIN supplier s ON s.supplier_id = p.product_id
    GROUP BY CODE";
$result = mysqli_query($dbc,$query);
while($row = mysqli_fetch_array($result)){
    // get html for each row
    $checkboxHtml = '';
    $idSups = explode('|||', $row['supplier_id_names']);
    foreach($idSups AS $s) {
        list($i,$s) = explode(':', $s);
        $checkboxHtml .= '<input type="checkbox" value="' . $i . '"> ' . $s;
    }
    // do something else...
}