在同一张表中将两个属性相关联起来,叫做自关联查询
一、创建好数据库表中的关联字段
上表中id和pid是相关联的属性,其中pid代表关联的父级id
二、在使用element-ui中的table分级展示中有一个children属性,我们需要配置一下前端代码,如果没有指定children,则默认为children
<el-table :data="tableData" stripe row-key="id" default-expand-all>
<el-table-column prop="id" label="编号" width="60" align="center">
</el-table-column>
<el-table-column prop="name" label="名称" align="center">
</el-table-column>
<el-table-column prop="remark" label="备注" align="center">
</el-table-column>
<el-table-column prop="createtime" label="创建时间" align="center">
</el-table-column>
<el-table-column prop="updatetime" label="更新时间" align="center">
</el-table-column>
<!-- 操作部分 -->
<el-table-column label="操作" align="center" width="240">
<template v-slot="scope">
<!-- socpe.row就是当前行的数据 -->
<el-button type="primary" @click="edit(scope.row)">编辑</el-button>
<el-button type="danger" @click="del(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
其中row-id 是必须要的
三、数据库查询语句编写
<resultMap id="categoryMap" type="com.example.springboot.entity.Category">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="remark" property="remark"/>
<result column="pid" property="pid"/>
<result column="createtime" property="createtime"/>
<result column="updatetime" property="updatetime"/>
<collection property="children" ofType="com.example.springboot.entity.Category" column="id" select="selectPid" />
</resultMap>
<select id="selectPid" resultType="com.example.springboot.entity.Category">
select * from category where pid=#{id}
</select>
<select id="listByCondition" resultMap="categoryMap">
select * from category
<where>
isnull(pid)<!--查询pid是空的作为以及菜单-->
<if test="name !=null and name != '' ">
name like concat('%',#{name},'%')
</if>
</where>
order by id desc
</select>
最后在resultMap中查询的数据都会集中在collection中,字段为children