通常使用 ID 和 parent 来存储类别树。在我的例子中,一个知识库,在article
表中每条记录(文章)都属于一个类别(带有一个字段catid
),在categories
表中每条记录都有一个ID
和parent
保存树结构。
article table
id | catid | date | subject | content
categories table
id | name | parent
问题是在将文章导出到 csv 或 excel 时,
id | category | date | subject | content
如何保持整个类别树,就像文章属于子类别时一样,我想要类别
grandpa/father/son/, or grandpa : father : son
然后可以在excel中打开csv,菜单->数据->文本到列,用“:”分隔,你会得到一个完整的树类别,而不仅仅是当前类别。
工作代码示例:
$query = 'SELECT `a`.`id` AS `ID`, concat(CASE WHEN ISNULL(`f`.`name`) THEN "" ELSE concat(`f`.`name`,":") END,CASE WHEN ISNULL(`e`.`name`) THEN "" ELSE concat(`e`.`name`,":") END,CASE WHEN ISNULL(`d`.`name`) THEN "" ELSE concat(`d`.`name`,":") END,CASE WHEN ISNULL(`c`.`name`) THEN "" ELSE concat(`c`.`name`,":") END,CASE WHEN ISNULL(`b`.`name`) THEN "" ELSE `b`.`name` END) AS `Category`, `a`.`subject` AS `Subject`,`a`.`content` AS `Content`,`a`.`dt` AS `Date Created`,
FROM articles as a
LEFT JOIN categories as b ON a.catid = b.id
LEFT JOIN categories as c ON b.parent = c.id
LEFT JOIN categories as d ON c.parent = d.id
LEFT JOIN categories as e ON d.parent = e.id
LEFT JOIN categories as f ON e.parent = f.id
WHERE (DATE(`dt`) BETWEEN \'' . $date_from . '\' AND \'' . $date_to . '\') order by id asc';
希望它对其他想要导出树结构字段的人有所帮助。